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
添加回答
举报