我想在输入中搜索单词列表。到目前为止,这是有效的。
swearWords = ["mittens", "boob"]
phrase = raw_input('> ')
listowords = [x.upper() for x in swearWords]
if any(word in phrase.upper() for word in listowords):
print 'Found swear word!'
else:
return
现在让我们说我要打印出被发现的单词是什么?
答案 0 :(得分:0)
这是一种方法(迭代不需要的单词,检查它是否存在):
undesired_words = ['blah', 'bleh']
user_input = raw_input('> ')
for word in undesired_words:
if word in user_input.lower():
print 'Found undesired word:', word
print 'User input was OK.'
答案 1 :(得分:0)
我已经用一些注释修改了你的代码,请查看:
swearWords = ["mittens", "boob"]
phrase = raw_input('> ')
# Here I've split the phrase into words so we can iterate through
phrase_words = phrase.split(' ')
# Now we iterate through both the words and the swear words and see if they match
for word in phrase_words:
for swear in swearWords:
if word.upper() == swear.upper():
print "Found swear word:", swear
这是我运行时得到的结果:
C:\Users\John\Desktop>temp.py
> These are some swear words. Like boob or mittens maybe. Are those really swear
words?
Found swear word: boob
Found swear word: mittens
希望这有帮助!