m0_72744985 2023-01-02 20:02 采纳率: 90%
浏览 56
已结题

python用一个文件替换与隐藏另一个文件中的敏感词

#宇宙中的每个星球都有自己对 "坏"字的定义。例如,"fat"这个词在"short-531"星球被认为是##一个粗话,那里的人对瘦子很着迷。
#同时,"cat "这个词在Woof星球中是完全不可接受的。
#作为行星地球的主要程序员之一,你被要求编写一个程序,从发往某个星球的信息中审查特定星球的#坏话,以避免两个星球之间可能的冲突。
#你的程序应该从名为"message.txt""badwords.txt"的文件中分别读取一个文本信息和一个坏#词列表。然后,该程序应寻找信息中的坏词,并通过以下方式进行审查。
#如果有替代词,就用替代词取代坏词,或
#保留坏字的第一个和最后一个字母,并将该字的中间字符改为星号。你的程序应该是不区分大小写#的。
#输入
#1.一个名为'message.txt'的文本文件,包含文本。
#2.一个名为 "badwords.txt"的文件,其中逐行存储坏词。如果存在一个坏词的替代品
#,它将出现在同一行的坏词之后。
#输出
#1.经过审查的文本(印在屏幕上)。

#输入文件message.txt
#dog are loyal animals that make people's lives
#more convenient and bring people a lot of joy.
#There are two types of dogs: large dogs and puppy,
#but they usually make some annoying noise,
#like woof and so on.
#they are also like bone and meat.
#Some people will make a doghouse for them.

#输入文件badwords.txt
#dog pup
#woof bark
#puppy
#dogs
#haven
#hell

##输出条件
#dog 将被 pup 所替代,woof 将被 bark 所替代
#puppy没有替代词将由 p***y 替代
#doghouse 包括dog但是它不被认为是坏词
  • 写回答

2条回答 默认 最新

  • |__WhoAmI__| 2023-01-02 20:16
    关注

    思路:
    需要先打开两个文件,读取其中的内容。可以使用 Python 的 open 函数打开文件,然后使用 read 或 readlines 方法读取文件的内容。

    然后需要将坏词从 "badwords.txt" 中读入到一个字典中,字典的键是坏词,值是替代品。可以使用 Python 的 split 函数将坏词和替代品分开。

    可以使用 Python 的字符串方法 replace 将坏词从信息中替换为替代品或替换为第一个字母和最后一个字母,并在中间用星号替换其他字符。可以使用 Python 的 len 函数获取坏词的长度,然后使用 range 函数遍历坏词的中间字符并将其替换为星号。
    最后将替换后的信息打印出来。

    # Open the message file and read the contents
    with open("message.txt", "r") as message_file:
        message = message_file.read()
    
    # Open the bad words file and read the contents
    with open("badwords.txt", "r") as badwords_file:
        badwords_lines = badwords_file.readlines()
    
    # Create a dictionary of bad words with their replacements
    badwords = {}
    for line in badwords_lines:
        words = line.split()
        if len(words) == 2:
            badwords[words[0]] = words[1]
        else:
            badwords[words[0]] = words[0][0] + "*" * (len(words[0]) - 2) + words[0][-1]
    
    # Replace the bad words in the message
    for badword in badwords:
        message = message.replace(badword, badwords[badword])
    
    # Print the censored message
    print(message)
    

    仅供参考,望采纳,谢谢。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 1月10日
  • 已采纳回答 1月2日
  • 创建了问题 1月2日

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题