[英]Find the position from a string in a substring in a sentence
我有一句話: Take 1 tablet in the morning and at noon for **1** week
我試圖找到對應1 1元的位置1 week
但是,如果我在我的句子中使用 re.search 的 '1' 元素,我會從對應於1 tablet
的1 個元素中獲得1 個位置
感謝 NLP,我可以提取元素for 1 week
。 所以我想在句子中找到for 1 week
的子串中的1 個元素。
你可以找到的跨度for 1 week
和跨度1
中for 1 week
(這是在這個例子中用處不大,但會更有趣了更復雜的正則表達式):
s = 'Take 1 tablet in the morning and at noon for 1 week'
import re
m = re.search('for 1 week', s)
start, stop = m.span()
m2 = re.search('1', m.group())
start2, stop2 = m2.span()
start+start2
輸出:
>>> start+start2
45
>>> s[45]
'1'
稍微復雜一點的例子:
m = re.search('(for|during) \d+ (week|day|month)', s)
start, stop = m.span()
m2 = re.search('\d+', m.group())
start2, stop2 = m2.span()
print(f'position {start+start2}: {s[start+start2]}')
輸出: position 45: 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.