【问题标题】:Fuzzy checking if each item of a list is contained in a given string模糊检查列表的每个项目是否包含在给定的字符串中
【发布时间】:2020-06-06 09:11:50
【问题描述】:
list = ['Apple','Banana','Cucumber']
string = 'The other day as I ate a bnana in the park'

for x in range(len(list)):
    if list[x] in string:
        do a little dance

这是我现在代码的要点,尽管我的实际字符串和列表要长得多。该字符串是用户提交的,所以我必须预料到拼写错误/速记/大写字母,并且没有用我能想到的每个拼写错误填写我的列表或解析字符串的每个单词,我不知道如何解决这个问题。

我正在寻找一个模糊的包含 if 语句。我已经查看了fuzzywuzzy 文档,但我不确定在这种情况下如何使它工作。

有这样的功能吗?

threshold = 80
for x in range(len(list):
     if fuzzy.contain(list[x],string) > threshold:
         do a little dance:

感谢您的帮助。

【问题讨论】:

  • 我查看了fuzzywuzzy 文档,但不确定如何在这种情况下使用它。 你能说得更具体些吗?

标签: python if-statement fuzzy-search


【解决方案1】:

我在fuzzywuzzy documentation 中找不到contain 方法,所以我想出了这个。您按单词拆分短语,然后以fuzzy 方式比较每个单词。根据您的特殊需要,您应该使用其他评级方法而不是token_sort_ratiothreshold 值。您可以在他们的github 中找到更多信息。

from fuzzywuzzy import fuzz

def fuzzy_contains_word(word, phrase, threshold):
    for phrase_word in phrase.split():
        if fuzz.token_sort_ratio(word, phrase_word) > threshold:
            return True
    return False


words = ['Apple','Banana', 'Cucumber']
user_input = 'The other day as I ate a bnana in the park'
threshold = 80

for word in words:
    if fuzzy_contains_word(word, user_input, 80):
        print(word, 'found in phrase: ', user_input)

>>> Banana found in phrase:  The other day as I ate a bnana in the park

注意:我收到了一个警告,说你应该安装 python-Levenshtein 包。

【讨论】:

  • 效果很好,谢谢。这也使我的下一个问题变得非常容易,即模糊地找到“Apple”而不是“Crab Apple”。再次感谢。
  • @GustavoCosta 好!如果它解决了您的问题,请考虑选择它作为接受的答案。
【解决方案2】:

来自文档:

threshold = 80
for x in range(len(list)):
     if fuzzy.WRatio(list[x],string) > threshold:
         do a little dance:

*免责声明我以前从未使用过fuzzy,但这应该可以。

【讨论】:

  • 这对我来说并没有像我以前想要的那样工作,但这是由于上限问题。 blur.WRatio() 完成了这个把戏。感谢您的帮助
  • 根据 Gustavo 的反馈进行了更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-26
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多