我希望用户输入歌词的程序(这将稍后将扩展到搜索一个网站,但我目前不需要帮助),该程序将告诉我,如果输入的信息包含一个词从一个列表。
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")这段代码只输出“这首歌是不道德的自由”。
发布于 2018-06-05 16:47:38
有几个想法我会推荐:
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)https://stackoverflow.com/questions/50705083
复制相似问题