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

标签 python list pattern-matching tuples

我有以下形式的列表:

[(“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/

相关文章:

c# - if 语句可以与使用模式匹配的变量赋值相结合吗?

c++ - 我该如何编码这个问题? (C++)

python - 如何将数组的前 N ​​个元素设置为零?

python - 将一系列字符串(加上数字)写入一行 csv

string - 是否可以使用 KMP 算法找到最长的子串?

macos - SwiftUI 对悬停事件不是很敏感

python - 将平面列表转换为python中的列表列表

python - 从 Excel CSV 读取并写入另一个文件时出现问题

python - Pandas 系列的groupby不起作用

Python - 始终将某些字符串附加到列表的末尾