我有一个非常大的单词列表(大约200k):
["cat", "the dog", "elephant", "the angry tiger"]
我用模糊创建了这个正则表达式:
regex = "(cat){e<3}|(the dog){e<3}|(elephant){e<3}|(the angry tiger){e<3}"
我输入了句子:
sentence1 = "The doog is running in the field"
sentence2 = "The elephent and the kat"
...
我想得到的是:
res1 = ["the dog"]
res2 = ["elephant", "cat"]
我试过这个例子:
re.findall(regex, sentence2, flags=re.IGNORECASE|re.UNICODE)
但这会输出我:
["elephent", "kat"]
知道如何用正确的单词得到正确的答案吗?我想要的是为每场比赛获得正则表达式捕获组,但我很难这样做。
也许我没有做到这一点,也许正则表达式不是好的方式,但带if item in list
循环的for
太长了,无法执行。
答案 0 :(得分:3)
可以通过手动构建正则表达式并命名组来完成:
import regex as re
a = ["cat", "the dog", "elephant", "the angry tiger"]
a_dict = { 'g%d' % (i):item for i,item in enumerate(a) }
regex = "|".join([ r"\b(?<g%d>(%s){e<3})\b" % (i,item) for i,item in enumerate(a) ])
sentence1 = "The doog is running in the field"
sentence2 = "The elephent and the kat"
for match in re.finditer(regex, sentence2, flags=re.IGNORECASE|re.UNICODE):
for key,value in match.groupdict().items():
if value is not None:
print ("%s: %s" % (a_dict.get(key), value))
elephant: elephent
cat: kat