我对Python语言知之甚少,如果你能帮助我,我将不胜感激。 我打算写一个代码,它基本上在输入的文本中搜索指定列表中的任何匹配单词(例如苹果,梨,汽车,房子等)。
提前致谢 詹姆斯
答案 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