python - 比较Python中2个不同列表中的单词,并在输出中用 "*"替换找到的单词

标签 python python-3.x

我试图发出用户作为输入给出的消息,就好像输入是“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/

相关文章:

python - 使用Python脚本获取未读电子邮件

python - 在不创建僵尸进程的情况下停止 Flask 中的后台进程

python - Django 。如何在表单 ManyToMany 字段中显示为选择(下拉列表)

mysql - pymysql 错误地将俄语文本写入数据库

Python 3从另一个函数更改函数中的变量

python - 在mean()之后绘图

python - 用户在 python 3.4.3 版中正确回答后如何打印 "correct"

python - H2O Predict() 函数的性能

python-3.x - 抓取youtube播放列表

python - 处理未分配的变量