我正在尝试让我的程序读取一条tweet,并通过查找我的字典在该tweet中查找公司名称。如果它找到一个公司名称,我希望它返回连接到该公司名称的滚动条。当字典键是一个单词时,我可以让它工作,但它不会显示它是一个像中国联通或EXPRESS脚本那样的多单词键。有什么建议吗?我知道拆分推文很难搜索多个单词的字符串,但这是我唯一能让它适用于像FACEBOOK和GOOGLE这样的单单词公司名称的方法。谢谢,这是我的代码。(输入只是推文,我现在只是手动输入它们,直到我弄清楚如何让它工作)
dictionary =
{'apple':'AAPL',
'google':'GOOG',
'alphabet':'GOOGL',
'microsoft':'MSFT',
'amazon':'AMZN',
'facebook':'FB',
'express scripts':'ESRX',
'china unicom':'CHU'}
data = "Google is in talks to acquire China Unicom"
tweet = data.lower()
if any(word in tweet for word in dictionary.keys()):
for x in tweet.split():
if x in dictionary.keys():
print(dictionary[x])我正在寻找的输出将是GOOG和CHU,但我只得到GOOG。
发布于 2018-02-13 04:55:24
我认为你在寻找一个有条件的理解:
dictionary = {'apple':'AAPL',
'google':'GOOG',
'alphabet':'GOOGL',
'microsoft':'MSFT',
'amazon':'AMZN',
'facebook':'FB',
'express scripts':'ESRX',
'china unicom':'CHU'}
data = 'Google is in talks to acquire China Unicom'
tweet = data.lower()
found = (dictionary[key] for key in dictionary.keys() if key in tweet)
for item in found:
print(item)输出:
GOOG
CHU发布于 2018-02-13 04:39:56
如果只需要打印连接到该公司名称的自动收报机,则可以使用:
dictionary =
{'apple':'AAPL',
'google':'GOOG',
'alphabet':'GOOGL',
'microsoft':'MSFT',
'amazon':'AMZN',
'facebook':'FB'}
data = input()
tweet = data.lower()
for key in dictionary.keys():
if key in tweet:
print(dictionary[key])无论输入的单词有多少,它都会为字典中的所有关键字运行,并检查是否与推文匹配,如果为真,则打印自动收报机
https://stackoverflow.com/questions/48754806
复制相似问题