如何比较字符串/ python词典中的单词?

时间:2019-04-19 09:43:39

标签: python string dictionary

我有一个字典项目,形式为

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

我需要检查像“我爱简单”这样的字符串是否包含该词典中的任何单词。

无法确定如何为此定义代码。

4 个答案:

答案 0 :(得分:2)

尝试:

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.")

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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

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

如果您的字典还有许多其他键,则需要全部检查它们:

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

答案 3 :(得分:0)

如果要使用循环:

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]