【问题标题】:Search string for dictionary key and if contains, display that keys value搜索字典键的字符串,如果包含,则显示该键值
【发布时间】:2018-07-23 02:45:18
【问题描述】:

我正试图让我的程序读取一条推文,并通过在我的字典中查找该推文中的公司名称。如果它找到公司名称,我希望它返回连接到该公司名称的代码。当字典键是一个单词时,我可以让它工作,但它不会像中国联通或 EXPRESS SCRIPTS 那样显示它是一个多词键。有什么建议?我知道拆分推文会使搜索多字字符串变得困难,但这是我可以使它适用于 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。

【问题讨论】:

    标签: python python-3.x dictionary twitter


    【解决方案1】:

    我认为您正在寻找条件理解:

    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
    

    【讨论】:

      【解决方案2】:

      如果您只需要打印与该公司名称相关的股票代码,您可以使用:

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

      无论输入多少单词,它都会针对字典中的所有键运行,并检查与推文的匹配,如果为真则打印自动收报机

      【讨论】:

      • 感谢您的帮助,但这并不能解决我的问题。我遇到的这个问题是它无法识别任何两个字长的公司名称,例如 Express Scripts - 它仅适用于像 Facebook 或 Google 这样的一个字长的公司名称。
      猜你喜欢
      • 2020-12-11
      • 2021-06-28
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 2021-07-09
      相关资源
      最近更新 更多