繁体   English   中英

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

[英]Python: Find closest matches on a list of tuples

我有以下形式的清单:

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

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

IN: "Apple I" Out: "AAPL"

IN:"BB" OUT:"BB"

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM