我在表单中有一个字典项目
{"value for money": ["rescheduled", "cost", "low", "high", "simplicity", "booking", "price-performance", "satisfied", "satisfaction", "pricing", "prices"]}
我需要检查一下像“I love simplicity”这样的字符串是否包含这本字典中的任何单词。
无法想出如何为此定义代码。
尝试:
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.")
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")
如果您的词典仅包含“物有所值”键,或者您只需要该键的值,则只需要知道输入字符串中的任何单词是否包含在这些值中:
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
如果你想使用循环:
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]