python - 如何不将整个单词 "king"匹配到 "king?"?

标签 python regex nlp

如何验证字符串中是否出现了确切的单词?

我需要考虑以下情况,例如“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/

相关文章:

python - 通过云存储桶更改通过云功能发送邮件

python - 找出哪个模块正在设置根记录器

python - 属性错误: 'DataFrame' object has no attribute 'target_names' - scikit

java - 如何使用 Open nlp 的分块解析器提取名词短语

python - 错误信息 "python-pylint ' C0103 :Invalid constant name"

python - 寻找一种在全大写单词上拆分字符串的好方法

c# - 用于识别网址的正则表达式

javascript - 在 Razor 中使用包含 '@' 的 javascript 正则表达式

nlp - 制作棕色簇

nlp - 情感分析(意见挖掘)中最具挑战性的问题是什么?