【问题标题】:How do i use difflib to return a list by searching for an element in the list?如何使用 difflib 通过搜索列表中的元素来返回列表?
【发布时间】:2020-12-02 12:48:37
【问题描述】:

我有一个看起来像这样的列表:

list123 = [["Title a1","100 Price","Company xx aa"], ["Title b1","200 Price","Company yy bb"], ["Title c1","300 Price","Company zz cc"]]

如何使用difflab.get_close_matches(或其他)通过搜索与搜索参数匹配的特定内部内部元素来返回整个内部列表?

我认为它会如何工作:

print(difflib.get_close_matches('Company xx a', list123))

预期输出/我想要的输出:

 ["Title a1","100 Price","Company xx aa"]

实际输出:

 []

我知道使用类似的东西:

for item in list123:
    if "Company xx aa" in item:
        print(item)

但我想使用 difflib 库(或其他东西)来允许更多的“人工”搜索,其中允许小的拼写错误。

如果我误解了函数的目的,还有其他可以实现我想要的吗?

【问题讨论】:

    标签: python search matching difflib


    【解决方案1】:

    问题是get_closest_matches的第二个参数应该是一个字符串列表,来自documentation:

    possibilities 是匹配单词的序列列表 (通常是字符串列表)。

    要解决您的问题,请执行以下操作:

    import difflib
    
    
    def key(choices, keyword='Company xx a'):
        matches = difflib.get_close_matches(keyword, choices)
        if matches:
            best_match, *_ = matches
            return difflib.SequenceMatcher(None, keyword, best_match).ratio()
        return 0.0
    
    
    list123 = [["Title a1", "100 Price", "Company xx aa"],
               ["Title b1", "200 Price", "Company yy bb"],
               ["Title c1", "300 Price", "Company zz cc"]]
    
    res = max(list123, key=key)
    
    print(res)
    

    输出

    ['Title a1', '100 Price', 'Company xx aa']
    

    思路是key函数会返回每个列表最佳匹配的相似度,然后你可以和max结合使用,找到最佳匹配的列表。

    【讨论】:

    • 感谢您的回复和努力,不胜感激!不幸的是我无法真正让它工作,似乎无论我使用什么作为关键字它总是返回第一行,我会尝试更多调试并返回。
    • @nordmanden 我把第一个列表放在第二个位置,它仍然返回它,所以如果你能带来更多细节......你用什么作为关键字?
    【解决方案2】:

    我试过了:

    list123 = [["Title a1", "100 Price", "Company xx aa"], ["Title b1",
                                                        "200 Price", "Company yy bb"], ["Title c1", "300 Price", "Cpswdaany zsdwz cawdc"]]
    for item in list123:
    
         print(difflib.get_close_matches("Company xx aa", item))
    

    您必须调整函数以指定“人类可读性如何”。 你也可以看看这个:Find the closest match between two string variables using difflib

    【讨论】:

    • 您好,感谢您的回复。我已经尝试过了,它并没有完全达到我的预期,这将为我的外部列表中的每个列表返回一个结果,即使结果为空。我会尝试修改它,看看我是否可以让它工作
    猜你喜欢
    • 1970-01-01
    • 2021-09-08
    • 2019-09-28
    • 1970-01-01
    • 2016-06-27
    • 2018-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多