fuzzywuzzy 与字典 python

fuzzywuzzy with dictionary python

下面的代码适用于数组:

g = ['hello how are you', 'how are you guys','what is your name']
s = ['how','guys']
MIN_MATCH_SCORE = 38
guessed_word = [word for word in g if fuzz.token_set_ratio(s, word) 
                                               >=  MIN_MATCH_SCORE]

输出: 'hello how are you''how are you guys'

如何用字典实现上面的内容?

p = [{1: 'hey guys'},
    {1: 'how are you all'},
    {1: 'hello guys, how are you doing'}]

预期输出:

{1: 'hello how are you'}, {1: 'how are you guys'}

希望我能得到一些回应。

from fuzzywuzzy import fuzz

p = [{1: 'hey guys'},
    {1: 'how are you all'},
    {1: 'what is your name'}]

s = ['how','guys']

MIN_MATCH_SCORE = 38
guessed_word= []

for i in p:
    for key,value in i.items():  #dict.items used to access the (key-value) pair of dictionary
        if(fuzz.token_set_ratio(s, value) >= MIN_MATCH_SCORE): #check the condition for each value , if it's satisfied create a dictionary & append it to result list
            dict={}
            dict[key]=value
            guessed_word.append(dict)

print(guessed_word) 

输出将是:

[{1: 'hey guys'}, {1: 'how are you all'}]

#这个也可以。 #g in p 在我的用例中。

guessed_word= []
for p in g:
    for k,l in p.items():
        l = [l]
        #d = [fuzz.token_set_ratio(s,l) >= MIN_MATCH_SCORE]
        d= [word for word in l if fuzz.token_set_ratio(s, word) >= 
          MIN_MATCH_SCORE]
        guessed_word.append({k:d})

您的列表理解可以转换为以下内容以使用词典。

guessed_word = [d for d in p if fuzz.token_set_ratio(s, list(d.values())[0]) >= 
                                                       MIN_MATCH_SCORE]

解释:

 d iterates over the dictionaries
 list(d.values())[0] is the string portion of the dictionary i.e. 'hey guys', etc.