Python从单词列表中搜索单词

时间:2014-03-11 23:21:14

标签: python-3.x

我对Python语言知之甚少,如果你能帮助我,我将不胜感激。 我打算写一个代码,它基本上在输入的文本中搜索指定列表中的任何匹配单词(例如苹果,梨,汽车,房子等)。

提前致谢 詹姆斯

1 个答案:

答案 0 :(得分:0)

您可以使用in运算符检查字符串是否包含其他子字符串 - 有关此问题的更多示例,请参阅this answer

# put the words you want to match into a list
matching_words = ["apple", "pear", "car", "house"]

# get some text from the user 
user_string = input("Please enter some text: ")

# loop over each word in matching_words and check if it is a substring of user_string
for word in matching_words:
    if word in user_string:
        print("{} is in the user string".format(word))

运行此功能

>>> Please enter some text: I'm in my house eating an apple
apple is in the user string
house is in the user string