我正在使用 Python 在描述(字符串)中搜索一些词(也是多标记)。
为此,我使用了这样的正则表达式
result = re.search(word, description, re.IGNORECASE)
if(result):
print ("Trovato: "+result.group())
但我需要的是获取匹配前后的前2个单词。例如,如果我有这样的东西:
Parking here is horrible, this shop sucks.
“这里是”是我要找的词。因此,在我将它与我的正则表达式匹配之后,我需要匹配前后的 2 个单词(如果存在的话)。
在例子中: parking 这里可怕,这
“ parking ”和可怕,这是我需要的词。
注意 描述是否很长,“这里是”的模式可以出现多次?
最佳答案
字符串操作呢?
line = 'Parking here is horrible, this shop sucks.'
before, term, after = line.partition('here is')
before = before.rsplit(maxsplit=2)[-2:]
after = after.split(maxsplit=2)[:2]
结果:
>>> before
['Parking']
>>> after
['horrible,', 'this']
关于python - 在字符串中搜索并获取Python中匹配前后的2个词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31713623/