Python:在元组列表上找到最接近的匹配项

时间:2018-07-05 22:23:41

标签: python list pattern-matching tuples

我有以下形式的列表:

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

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

IN: "Apple I" Out: "AAPL"

IN:"BB" OUT:"BB"

我尝试使用difflib.get_close_matches,但在寻找一种将公司名称和股票代码保持在一起的好方法时遇到了困难

1 个答案:

答案 0 :(得分:3)

  

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

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

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'])