【问题标题】:fuzzywuzzy with dictionary python字典python的fuzzywuzzy
【发布时间】:2021-07-12 09:59:22
【问题描述】:

以下代码适用于数组:

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]

输出: '你好' '你们好吗'

如何用字典实现以上功能?

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'}

希望我能得到一些回应。

【问题讨论】:

  • 这是一个非常基本的遍历逻辑。你在问出来之前有没有试过这个?您需要遍历的只是列表 p 的元素,它们是 dict,因此获取它们的值。
  • 您能举个例子吗?
  • 请看我的预期输出。
  • guess_word 的列表理解中存在错误。如果应该是 word 而不是 word[1] (即 word[1] 只是一个字母)。当前代码guessed_word是[]。
  • 现在可以使用了,请检查一下,刚刚从 word 中删除了[0]

标签: python arrays list fuzzywuzzy


【解决方案1】:
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: '大家好'}, {1: '你们好吗'}]

【讨论】:

    【解决方案2】:

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

    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.
    

    【讨论】:

      【解决方案3】:

      #这个也可以。 #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})
      

      【讨论】:

        猜你喜欢
        • 2020-11-30
        • 1970-01-01
        • 2012-01-22
        • 2019-08-29
        • 1970-01-01
        • 2018-09-28
        • 2013-05-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多