|
发表于 2017-9-17 12:15:43
|
显示全部楼层
这段代码中存在的问题蛮多
首先,你这个问题是编码引起的
解决编码参数如下代码:
- 安装chardet
- https://pypi.python.org/pypi/chardet
- import chardet
- #以rb读取文件返回文件的编码(用到了chardet类)
- with open(file_name, 'rb') as f:
- raw = f.read()
- result = chardet.detect(raw)
- encoding = result['encoding']
- lines = 0
- with open(file_name,encoding=encoding) as f:
- print('正在分析文件:%s ...' % file_name)
- try:
- for each_line in f:
- lines += 1
- except Exception as reason:
- print(str(reason)) # 读取出错显示错误信息......
- print('%s -> %s' % (file_name,lines))
- return lines
复制代码
你的代码我修改后,我觉得这样更理想,还有就是打开文件建议用with,代码如下:
- import chardet
- #实现替换函数
- def replace(filename,o,n):
- #处理编码问题
- with open(filename, 'rb') as f:
- raw = f.read()
- result = chardet.detect(raw)
- encoding = result['encoding']
- #读取文件
- with open(filename,encoding=encoding) as f:
- text = f.read()
- time_appear = text.count(o)
- print('文件%s中共有%d个【%s】'%(filename,time_appear,o))
- decide = input('您确定要把所有的【%s】替换为【%s】嘛?'%(o,n))
- if decide == 'yes':
- newtext = text.replace(o,n)
- return newtext
- filename = input('请输入要打开的文件名:')
- old = input('请输入需要替换的单词或字符:')
- new = input('请输入新的单词或字符:')
- #替换
- newfulltext = replace(filename,old,new)
- #最后写入
- with open(filename, 'w') as f:
- f.write(newfulltext)
复制代码
|
|