首页 > 解决方案 > Python - 如果一个“好”字和一个“坏”字包含在一个字母中,打印出来

问题描述

我有一个坏词列表和一个好词列表。我的想法是首先搜索好词,然后查看字母中的哪个含义包含这些好词,但如果该含义还包含一个坏词 - 那么它不应该打印出含义。

ETC:

Good word: "Lo", "Yes"
Bad word: "Hate", "Not"
text_roman: "Hello guys. My name is Lo and I hate to code :')"

含义:“大家好。我的名字是 Lo,我讨厌编码 :')”<--“只是个玩笑!!

所以意思如果它搜索那个意思,它应该告诉我们有一个包含好的意思,然后检查它是否包含坏词。如果是这样,那么我们不想打印出含义,但如果它不包含任何坏词,那么我们应该将其打印出来。

我尝试编码的方式是:

text_roman = "Hello guys. My name is Lo and I hate to code :')"
good_word = ["Lo", "Yes"]
bad_word = ["Hate", "Not"]
for text in good_word:
   if text in text_roman:
      print("Yay found word " + text_roman)
      for bad_text in bad_word:
         if bad_text not in text_roman:
             print("Yay no bad words!")

当我尝试这个时,不幸的是,输出也给出了所有包含坏词的词

标签: pythonfor-loopif-statement

解决方案


我会先遍历那些不好的词,然后跳过它们。然后,如果没有跳过,检查一个好词

good_word = ["Lo", "Yes"]
bad_word = ["Hate", "Not"]

has_bad = False
for b in bad_word:
   if b in text_roman:
       has_bad = True 
       continue
   for g in good_word:
      if g in text_roman:
          print("Yay found word " + g + " in text_roman")
if not has_bad:
    print("Yay no bad words!")

注意:in区分大小写,因此"Hate" in "I hate case-sensitivity"为 False


推荐阅读