首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检查字符串是否包含列表中的单词

如何检查字符串是否包含列表中的单词
EN

Stack Overflow用户
提问于 2018-06-05 16:40:41
回答 1查看 1K关注 0票数 2

我希望用户输入歌词的程序(这将稍后将扩展到搜索一个网站,但我目前不需要帮助),该程序将告诉我,如果输入的信息包含一个词从一个列表。

代码语言:javascript
复制
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")

这段代码只输出“这首歌是不道德的自由”。

EN

回答 1

Stack Overflow用户

发布于 2018-06-05 16:47:38

有几个想法我会推荐:

  • 使用str.split按空格拆分。
  • 使用set进行O(1)查找。这是由{}表示的,而不是用于列表的[]
  • 将您的逻辑封装在一个函数中。这样,你就可以简单的return一句脏话就够了。这样您就不再需要else语句了。
  • 使用函数意味着不需要设置默认变量,然后在适用的情况下重新分配。
  • 使用str.casefold捕获大小写单词。

下面是一个例子:

代码语言:javascript
复制
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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50705083

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档