我有以下形式的列表:
[(“AAPL”、“苹果公司”)、(“TSLA”、“特斯拉公司”)、(“BB”、“黑莓有限公司”)]
我想在用户输入公司名称或符号时找到最接近的匹配项。例如:
IN:“Apple I”
输出:“AAPL”
IN:“BB”
输出:“BB”
我尝试使用difflib.get_close_matches但我无法找到将公司名称和股票代码保持在一起的好方法
最佳答案
good way to keep the company name and ticker symbol together
我们只需要为它做一个中间映射:
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'])
关于Python:在元组列表中查找最接近的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51200646/