python - 使用 'any' 查找字符串是否包含列表的一部分,然后将找到的部分放入变量中?

标签 python python-3.x

我在字典中有一个潜在命中的列表。我想获取用户输入,然后搜索字典以查看是否在字符串中找到任何单词。如果是(无论是哪个)我想将找到的单词分配给一个变量。我就是不明白最后一部分;将找到的元素存储到变量中。因此,如果我输入“告诉我有关荷鲁斯的信息”,它将获取关键字“荷鲁斯”并打印字典中该值的信息。

lookup_dict = {'horus': "description of Horus.", 'anubis': "description of Anubis."}

userin = input(":  ")
res = any(ele in userin for ele in lookup_dict)
if res is True:
    # somehow print the description from the associated element

最佳答案

如果您只关心该单词是否是输入字符串的一部分,而不介意输入字符串中是否有两个或多个单词:

lookup_dict = {'horus': "description of Horus.", 'anubis': "description of Anubis."}

userin = input(":  ")
for word, definition in lookup_dict.items():
    if word in userin:
        print(definition)

关于python - 使用 'any' 查找字符串是否包含列表的一部分,然后将找到的部分放入变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58147556/

相关文章:

python-3.x - 使用 lambda 函数作为排序的键

Python - 为什么这段代码被认为是一个生成器?

Python 增长字典或增长数据框 - 在循环中追加

python-3.x - 值错误: DataFrame constructor not properly called when convert Json data to Dataframe

python - 如何使用 os.listdir() 忽略隐藏文件?

python - 如何在文本文件中搜索用户输入的单词列表?

python - 分析 fuse-python

python-3.x - tf.metrics.accuracy 未按预期工作

python - 字符 LSTM 不断生成相同的字符序列

python - 如何通过唯一键值对有序字典列表中的字典进行寻址?