我希望用户输入歌词到该程序(稍后将扩展到搜索网站,但我目前不需要帮助),程序将告诉我输入的信息是否包含列表中的单词。
banned_words = ["a","e","i","o","u"] #This will be filled with swear words
profanity = False
lyrics = input ("Paste in the lyrics: ")
for word in lyrics:
if word in banned_words:
print("This song says the word "+word)
profanity = True
if profanity == False:
print("This song is profanity free")
此代码只输出'这首歌是亵渎性的。'
答案 0 :(得分:2)
我建议有几个想法:
str.split
按空格分割。set
进行O(1)查找。这由{}
表示,而不是用于列表的[]
。return
。然后,您不再需要else
语句。str.casefold
抓住大写和小写字词。以下是一个例子:
banned_words = {"a","e","i","o","u"}
lyrics = input("Paste in the lyrics: ")
def checker(lyrics):
for word in lyrics.casefold().split():
if word in banned_words:
print("This song says the word "+word)
return True
print("This song is profanity free")
return False
res = checker(lyrics)