[英]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.