繁体   English   中英

比较python中2个不同列表中的单词并在输出中用“*”替换找到的单词

[英]Comparing words in 2 different list in python and replacing the found words with "*" in output

我试图使用户作为输入提供的消息发出哔哔声,好像输入是“到底是什么”,其中“见鬼”出现在名为“banned.txt”的文件中的禁用词列表中,以便输出变为“什么**”。

我是 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()

输入:什么鬼
预期输出:什么****

不要将您的 msg 拆分成一个列表,而是在列表中搜索被禁止的词。

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)

你的问题在于:

bannedwords=[infile.read().split("\n")]
userwords=[msg.split(" ")]

split 命令已经将单词放入一个数组中,因此您将它们包装在两个数组中,得到:

[['heck', '']]
[['what', 'the', 'heck']]

分别作为禁用词列表和消息中的词列表。

从定义中删除[]并使用:

bannedwords=infile.read().split("\n")
userwords=msg.split(" ")

并且您的代码应该可以正常工作。 您也可以检查每个单词是否在禁用单词列表中,例如:

bannedwords=infile.read().split("\n")
userwords=msg.split(" ")

for uword in userwords:
    # An easier way to check if the word is banned.
    if(uword in bannedwords):
        # If it's banned, print one * for each letter in the word.
        print("*" * len(uword))
    else:
        print(uword)

'what the heck' 的输入给出了以下输出:

what
the
****

以下解决方案可能适合您。 这也会从msg字符串的末尾删除标点符号,同时将msg bannedwords替换为“*”:

from string import punctuation
bannedwords = ["heck", "darn"]
msg = input("What message would you like to censor?: ")
for word in msg.rstrip(punctuation).split(' '):
    if word in bannedwords:
        new_word = '*' * len(word)
        msg = msg.replace(word, new_word)
print(msg)

#Output:
What message would you like to censor?: What the heck?
What the ****?

#Another attempt:
What message would you like to censor?: darn it!
**** it!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM