【问题标题】:Python: Find closest matches on a list of tuplesPython:在元组列表上查找最接近的匹配项
【发布时间】:2018-07-05 22:23:41
【问题描述】:

我有一个如下形式的列表:

[("AAPL", "Apple Inc."), ("TSLA", "Tesla Inc."), ("BB", "BlackBerry Limited")]

我想在用户输入公司名称或符号时找到最接近的匹配项。例如:

IN: "Apple I" Out: "AAPL"

IN:"BB" OUT:"BB"

我尝试使用 difflib.get_close_matches,但无法找到将公司名称和股票代码保持在一起的好方法

【问题讨论】:

    标签: python list pattern-matching tuples


    【解决方案1】:

    将公司名称和股票代码放在一起的好方法

    我们只需要为它做一个中间映射:

    import difflib
    
    data = [("AAPL", "Apple Inc."), ("TSLA", "Tesla Inc."), ("BB", "BlackBerry Limited")]
    index = {name.lower(): symbol for symbol, name in data}
    index.update({symbol.lower(): symbol for symbol, name in data})
    
    def search_for_company(text):
        return set(
            index[name_or_symbol]
            for name_or_symbol in difflib.get_close_matches(text.lower(), index.keys())
        )
    
     print search_for_company('Apple I')  # set(['AAPL'])
     print search_for_company('BB')  # set(['BB'])
     print search_for_company('aapl')  # set(['AAPL'])
    

    【讨论】:

    • 输入aapl 产生一个空列表
    • @APorter1031 非常感谢,我彻底改变了我的代码
    猜你喜欢
    • 2021-02-08
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多