#宇宙中的每个星球都有自己对 "坏"字的定义。例如,"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但是它不被认为是坏词
python用一个文件替换与隐藏另一个文件中的敏感词
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
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无用
悬赏问题
- ¥15 宇视监控服务器无法登录
- ¥15 PADS Logic 原理图
- ¥15 PADS Logic 图标
- ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
- ¥20 气象站点数据求取中~
- ¥15 如何获取APP内弹出的网址链接
- ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
- ¥50 STM32单片机传感器读取错误
- ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
- ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)