给你个参考,文本替换还是用re方面。import re
import os
def ckfile(file):
if os.path.exists(file):
return True
else:
print(f'{file}不存在!')
exit(1)
def FileToStr(file):
with open(file, encoding='utf-8') as f:
return f.read()
def StrToFile(str, file):
with open(file, 'w', encoding='utf-8') as f:
f.write(str)
def main():
file = input('请输入文件名:')
oldwd = input('请输入要替换的单词:')
newwd = input('请输入新的单词:')
ckfile(file)
temp_str = FileToStr(file)
on = re.findall(oldwd, temp_str)
if on:
print(f'{file}中共有{len(on)}个{oldwd}。')
ry = input('是否替换?Y/N:')
if ry in ['y', 'Y']:
result = re.sub(oldwd, newwd, temp_str)
StrToFile(result, file)
print('替换完成!')
else:
print('已取消替换!')
else:
print(f'{file}没有{oldwd}这个词。')
exit(1)
if __name__ == "__main__":
main()
|