如何比较字符串/ python字典中的单词? [关闭]

问题描述 投票:-3回答:4

我在表单中有一个字典项目

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

我需要检查一下像“I love simplicity”这样的字符串是否包含这本字典中的任何单词。

无法想出如何为此定义代码。

python string dictionary
4个回答
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
投票
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")

1
投票

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

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

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]

© www.soinside.com 2019 - 2024. All rights reserved.