我试图发出用户作为输入给出的消息,就好像输入是“what the heck”,其中“heck”出现在名为“banned.txt”的文件中的禁止单词列表中,以便输出变成“what the ****”。
我是 python 的新手,到目前为止,我已经根据传递的输入创建了两个列表以及存在禁用单词的列表,我在比较这两个列表中的单词时遇到了困难,有人可以解释吗我如何解决这个问题。
from cs50 import get_string
import sys
def main():
if len(sys.argv) != 2:
print("Usage: python bleep.py dictionary")
exit(1)
print("What message would you like to censor?")
msg=get_string()
infile=open(sys.argv[1],'r')
bannedwords=[infile.read().split("\n")]
userwords=[msg.split(" ")]
for uword in userwords:
for bword in bannedwords:
if(uword==bword)
#do something.....but its not comparing words
if __name__ == "__main__":
main()
输入:到底是什么
预期输出:什么****
最佳答案
不要将您的消息拆分为一个列表,而是在其中搜索被禁止的单词。
for word in bannedwords:
if word in msg:
new_word = "*" * len(word)
new_msg = msg.replace(word, new_word)
如果您想直接测试它,请使用:
bannedwords = ["banned", "other"]
msg = "the next word is banned"
new_msg = ""
for word in bannedwords:
if word in msg:
new_word = "*" * len(word)
new_msg = msg.replace(word, new_word)
print(new_msg)
关于python - 比较Python中2个不同列表中的单词,并在输出中用 "*"替换找到的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54040024/