[英]Search in a string and obtain the 2 words before and after the match in Python
我正在使用Python在描述(字符串)中搜索一些单词(也是多标记)。
要做到这一点,我正在使用这样的正则表达式
result = re.search(word, description, re.IGNORECASE)
if(result):
print ("Trovato: "+result.group())
但我需要的是在比赛前后获得前2个单词。 例如,如果我有这样的事情:
停车在这里很可怕,这家店很糟糕。
“ 这里是 ”这个词我要找的。 所以在我将它与我的正则表达式匹配后,我需要在比赛之前和之后的2个单词(如果存在)。
在这个例子中: 停车在这里很可怕,这个
“停车”,可怕,这是我需要的话。
注意说明驾驶室很长,“这里”的模式可以出现多次?
字符串操作怎么样?
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']
根据您的澄清,这变得有点复杂。 下面的解决方案涉及搜索模式实际上也可能在前两个或两个后续单词中的情况。
line = "Parking here is horrible, here is great here is mediocre here is here is "
print line
pattern = "here is"
r = re.search(pattern, line, re.IGNORECASE)
output = []
if r:
while line:
before, match, line = line.partition(pattern)
if match:
if not output:
before = before.split()[-2:]
else:
before = ' '.join([pattern, before]).split()[-2:]
after = line.split()[:2]
output.append((before, after))
print output
我的例子的输出是:
[(['停车'],['可怕,','这里']),(['是','可怕,'],['很棒','这里']),(['是','伟大的'],['平庸','这里']),(['是','平庸'],['这里','是']),(['here','is'],[] )]
我会这样做( 编辑:添加锚点以涵盖大多数情况 ):
(\S+\s+|^)(\S+\s+|)here is(\s+\S+|)(\s+\S+|$)
像这样你将总是有4组(可能需要修剪)具有以下行为:
更正了演示链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.