【问题标题】:How to compare words in a string/python dictionary? [closed]如何比较字符串/python字典中的单词? [关闭]
【发布时间】:2019-09-09 14:31:40
【问题描述】:

我在表单中有一个字典项

 {"value for money": ["rescheduled", "cost", "low", "high", "simplicity", "booking", "price-performance", "satisfied", "satisfaction", "pricing", "prices"]}

我需要检查“I love simple”之类的字符串是否包含这本词典中的任何单词。

不知道如何为此定义代码。

【问题讨论】:

  • 基本for循环可以解决这个问题,你能详细说明问题吗?

标签: python string dictionary


【解决方案1】:

试试:

mydict =  {"value for money": ["rescheduled", "cost", "low", "high", "simplicity", "booking", "price-performance", "satisfied", "satisfaction", "pricing", "prices"]}
mystring = "I love simplicity"
if any((word in mystring) for word in mydict["value for money"]):
    print("Found one.")

【讨论】:

    【解决方案2】:
    d={"value for money": ["rescheduled", "cost", "low", "high", "simplicity", "booking", "price-performance", "satisfied", "satisfaction", "pricing", "prices"]}
    s="I love simplicity" 
    
    for w in s.split(' '):
      if w in d["value for money"]:
        print (w," is in value for money")
    

    【讨论】:

      【解决方案3】:

      如果您的字典仅包含“物有所值”键,或者您只需要该键的值,并且您只需要知道输入字符串中的任何单词是否在这些值中:

      def is_in_dict(string, dictionary):
          for word in string.split():
              if word in dictionary['value for money']:
                  return True
          return False
      

      如果您的 dict 有许多其他键并且您需要全部检查:

      def is_in_dict(string, dictionary):
          for word in string.split():
              for values in dictionary.values():
                  if word in values:
                      return True
          return False
      

      【讨论】:

        【解决方案4】:

        如果你想使用循环:

        string = 'I love simplicity'
        dictionary =  {"value for money": ["rescheduled", "cost", "low", "high", "simplicity", "booking", "price-performance", "satisfied", "satisfaction", "pricing", "prices"]}
        
        for word in dictionary['value for money']:
            if word in string:
                print(word)
        

        如果你想使用生成器:

        [word for word in dictionary['value for money'] if word in string]

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-01-03
          • 1970-01-01
          • 2021-05-09
          • 2016-06-10
          • 2015-11-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多