首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >模糊检查列表的每一项是否包含在给定的字符串中

模糊检查列表的每一项是否包含在给定的字符串中
EN

Stack Overflow用户
提问于 2020-02-22 06:38:47
回答 2查看 48关注 0票数 0
代码语言:javascript
复制
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文档,但我不确定在这种情况下如何让它工作。

有这样的函数吗?

代码语言:javascript
复制
threshold = 80
for x in range(len(list):
     if fuzzy.contain(list[x],string) > threshold:
         do a little dance:

我很感谢你的帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-22 07:11:32

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

代码语言:javascript
复制
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包。

票数 1
EN

Stack Overflow用户

发布于 2020-02-22 07:11:04

从文档中:

代码语言:javascript
复制
threshold = 80
for x in range(len(list)):
     if fuzzy.ratio(list[x],string) > threshold:
         do a little dance:

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60347118

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档