import re
#敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。
class Get_Filterworf:
def __init__(self, file_path):
self.sensitive_words = []
# 读取敏感词文件并保存在列表中
with open(file_path, 'r', encoding='utf-8') as filterword:
for line in filterword:
s = re.split(r'[,.\n]', line)
self.sensitive_words.extend(filter(lambda x: x.strip(), s))
# 检测是否含有敏感词
def getfilter(self, words):
for word in self.sensitive_words:
if re.search(r'\b' + re.escape(word) + r'\b', words):
return 'Freedom'
return 'Human Rights'
# 创建 Get_Filterworf 的实例并传入敏感词文件路径
g = Get_Filterworf(r'C:\Users\dell\Desktop\filtered_words.txt')
# 测试输入
print(g.getfilter('北京南港湾'))
遇到的问题:
1.
一开始在读入时提示报错UnicodeDecodeError: 'gbk' codec can't decode byte 0x98 in position 16: illeg
上面报错的意思就是,默认以gbk的方式读取数据,但是文本数据是utf-8类型的,这是需要用到另一个参数encoding,也就是把它编码成与文本一样类型的格式,下面的代码encoding="utf-8"就是要修改的地方,如果不写编码格式,默认是encoding="gbk"的,在读入是后面加上encoding=‘utf8’就可以了
2.
在Python中,以双下划线开头的属性或方法默认是私有的,意味着它们只能在定义它们的类内部访问,而不能在类的外部或子类中直接访问。但是,在类的方法内部,你可以使用 self.__attr 来访问私有属性,因为Python会对属性名进行名称修饰(name mangling),将其变为 _ClassName__attr 的形式。这种机制使得在类内部能够访问私有属性,但不推荐在类的外部直接使用这种形式访问私有属性。
在你的代码中,__str 是一个私有属性,你在类的外部尝试使用 __str 来访问它,这是无法直接访问的。要在类的内部访问私有属性,应该使用 self.__str。同时,如果需要在类的外部访问私有属性,应该提供相应的公有方法进行访问,而不是直接访问私有属性
**敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「是个好城市」。
import re
# 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。
class Get_Filterworf:
def __init__(self, file_path):
self.sensitive_words = []
# 读取敏感词文件并保存在列表中
with open(file_path, 'r', encoding='utf-8') as filterword:
for line in filterword:
s = re.split(r'[,.\n]', line)
self.sensitive_words.extend(filter(lambda x: x.strip(), s))
# 检测是否含有敏感词
def getfilter(self, words):
filtered_words = words
for word in self.sensitive_words:
print(word)
filtered_words = re.sub(r'\b' + re.escape(word) + r'\b', '*' * len(word), filtered_words)
return filtered_words
# 创建 Get_Filterworf 的实例并传入敏感词文件路径
g = Get_Filterworf(r'C:\Users\dell\Desktop\filtered_words.txt')
# 测试输入
print(g.getfilter('北京南港湾'))
将文本文件写到 student.xls 文件中
import json
from openpyxl import Workbook
def json_to_excel(json_file, excel_file):
# 打开JSON文件并加载学生信息
with open(json_file, 'r', encoding='utf-8') as f:
student_info = json.load(f)
# 创建一个新的Excel工作簿
wb = Workbook()
ws = wb.active
# 写入表头
ws.append(["学号", "姓名", "语文成绩", "数学成绩", "英语成绩"])
# 遍历学生信息,逐行写入Excel文件
for key, value in student_info.items():
ws.append([int(key)] + value)
# 保存Excel文件
wb.save(excel_file)
# 调用函数将JSON文件写入Excel文件
json_to_excel('student.txt', 'student.xlsx')