4 回答

TA貢獻1817條經驗 獲得超6個贊
只需使用一個簡單的列表:
text = "The world is a small place, we should try to take care of it"
d = text.split()
try:
idx = d.index('world')
print("{} {} {}".format(d[idx - 1], d[idx], d[idx + 1]))
except ValueError:
print("Not in the text.")
哪個產量
The world is
您需要在這里考慮負指數。

TA貢獻1785條經驗 獲得超8個贊
您可以使用?
量詞
要匹配單詞“try”和上一個或下一個單詞的一個字符:
試試看
(. )?try( .)?
解釋:
(. )?
:匹配一個字符,然后匹配一個空格零次或一次try
: 字面意思是“嘗試”( .)?
:匹配空格和一個字符零次或一次
如果您想匹配單詞字符或整個單詞,您可以修改.
來匹配。試試看\w
\w+
要匹配兩側最多兩個?
單詞,您可以將 the 替換為{0, 2}
?

TA貢獻1859條經驗 獲得超6個贊
import re
text = "The world is a small place, we should try to take care of it"
sub = re.compile(r'(?P<all>(\w*)\s*try\s*(\w*))')
rez = [m.groupdict() for m in sub.finditer(text)]
for item in rez:
print(item["all"])
text = "try to take care of it"
rez = [m.groupdict() for m in sub.finditer(text)]
for item in rez:
print(item["all"])
我測試了它:
The world is a small place, we should try to take care of it
try to take care of it
并得到:
should try to
try to
https://regex101.com/r/DlSJsJ/1
添加回答
舉報