如何验证字符串中是否出现了确切的单词?
我需要考虑以下情况,例如“king”之类的词紧跟问号,如下例所示。
unigrams 这应该是 False
In [1]: answer = "king"
In [2]: context = "we run with the king? on sunday"
n_grams 这应该是 False
In [1]: answer = "king tut"
In [2]: context = "we run with the king tut? on sunday"
unigrams 这应该是 True
In [1]: answer = "king"
In [2]: context = "we run with the king on sunday"
n_grams 这应该是 True
In [1]: answer = "king tut"
In [2]: context = "we run with the king tut on sunday"
正如人们提到的,对于 unigram 的情况,我们可以通过将字符串拆分为列表来处理它,但这对 n_grams 不起作用。
阅读一些帖子后,我认为我应该尝试使用后视来处理,但我不确定。
最佳答案
return answer in context.split():
>>> answer in context.split()
False
你不需要正则表达式。
如果您正在寻找关键字:
all([ans in context.split() for ans in answer.split()])
将与 "king tut"
一起使用,但这取决于您是否要匹配如下字符串:
"we tut with the king"
如果不这样做,您仍然需要正则表达式 (although you should probably use one) ,假设您只想考虑整个术语(默认情况下通过 .split()
正确拆分):
def ngram_in(match, string):
matches = match.split()
if len(matches) == 1:
return matches[0] in string.split()
words = string.split()
words_len = len(words)
matches_len = len(matches)
for index, word in enumerate(words):
if index + matches_len > words_len:
return False
if word == matches[0]:
for match_index, match in enumerate(matches):
potential_match = True
if words[index + match_index] != match:
potential_match = False
break
if potential_match == True:
return True
return False
这是 O(n*m)
在最坏情况下的字符串,大约是正则表达式在正常字符串上的一半。
>>> ngram_in("king", "was king tut a nice dude?")
True
>>> ngram_in("king", "was king? tut a nice dude?")
False
>>> ngram_in("king tut a", "was king tut a nice dude?")
True
>>> ngram_in("king tut a", "was king tut? a nice dude?")
False
>>> ngram_in("king tut a", "was king tut an nice dude?")
False
>>> ngram_in("king tut", "was king tut an nice dude?")
True
关于python - 如何不将整个单词 "king"匹配到 "king?"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939370/