先以只读模式打开文件,readlines()读取所有行
再以只写方式进行读写打开对每一行替换内容,并保存到新的列表中。
“风力发电机组”替换为“风机”,“发电机组”替换为“风机”
file = 'data/dict/maintain_dict.txt'
with open(file, 'r', encoding='utf-8') as f:
alllines = f.readlines() # list形式返回txt的所有行 ['打力矩\n', '查找箱变漏油处\n',...]
# print(lines)
with open(file, 'w', encoding='utf-8') as f:
for eachline in alllines:
eachline = eachline.replace(r'风力发电机组', '风机')
eachline = eachline.replace(r'发电机组', '风机')
f.write(eachline)