對于一句話
'Foo bar was open on 12.03.2022 and closed on 3.05.22.'與各自list = [12.03.2022, 4.04.2022, 3.05.22]
如果可以在句子中找到串列中的日期,我想將句子中的開始和結束索引作為元組。
在這種情況下:[(20,29), (45, 51)]
我通過正則運算式找到了日期,但我無法獲得索引。
DAY = r'(?:(?:0)[1-9]|[12]\d|3[01])' # day can be from 1 to 31 with a leading zero
MONTH = r'(?:(?:0)[1-9]|1[0-2])' # month can be 1 to 12 with a leading zero
YEAR1 = r'(?:(?:20|)\d{2}|(?:19|){9}[0-9])' # Restricted the year to begin in 20th or 21st century
# Also the first two digits may be skipped if data is represented as dd.mm.yy
YEAR2 = r'(?:20\d{2}|199[0-9])'
BEGIN_LINE1 = r'(?<!\w)'
DELIM1 = r'(?:[\,\/\-\._])'
DELIM2 = r'(?:[\,\/\-\._])?'
# combined, several options
NUM_DATE = f"""(?P<date>
(?:
# DAY MONTH YEAR
(?:{BEGIN_LINE1}{DAY}{DELIM1}{MONTH}{DELIM1}{YEAR1})
|
(?:{BEGIN_LINE1}{DAY}{DELIM1}{MONTH})
|
(?:{BEGIN_LINE1}{MONTH}{DELIM1}{YEAR1})
|
(?:{BEGIN_LINE1}{DAY}{DELIM2}{MONTH}{DELIM2}{YEAR2})
|
(?:{BEGIN_LINE1}{MONTH}{DELIM2}{YEAR2})
)
)"""
myDate = re.compile(f'{NUM_DATE}', re.IGNORECASE | re.VERBOSE | re.UNICODE)
def find_date(subject):
"""_summary_
Args:
subject (_type_): _description_
Returns:
_type_: _description_
"""
if subject is None:
return subject
dates = list(set(myDate.findall(subject)))
return dates
uj5u.com熱心網友回復:
使用re.search:
sent = 'Foo bar was open on 12.03.2022 and closed on 3.05.22.'
date_list = ['12.03.2022', '4.04.2022', '3.05.22']
hits = [re.search(date, sent) for date in date_list if re.search(date, sent)]
對于第xth 場比賽,
hits[x].span()會給你指數- 并將
hits[x].group()回傳匹配的子字串
uj5u.com熱心網友回復:
使用常規 for 回圈。
sent = 'Foo bar was open on 12.03.2022 and closed on 3.05.22.'
list = ['12.03.2022', '4.04.2022', '3.05.22']
tup = []
for i in list:
if i in sent:
start_index = sent.index(i)
end_index = start_index len(i) - 1
tup.append((start_index, end_index))
使用串列理解:
tup = [(sent.index(i), sent.index(i) len(i) - 1) for i in list if i in sent]
print(tup)
>>>> [(20, 29), (45, 51)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520239.html
標籤:Python细绳列表索引
下一篇:更改串列中字串的某些索引值
