用pycharm 作一个文本编辑测试,代码为下图:运行后hello文本数据和hello world里面的完全一样,没有实现更改。电脑系统为 macOS 10.13.4 (17E199) python版本3.7
f=open('/Users/zhangxiukang/Desktop/hello world.rtf','r',encoding='utf-8')
f_new=open('/Users/zhangxiukang/Desktop/hello.txt','w',encoding='utf-8')
for line in f:
if '昨日' in line:
line=line.replace('昨日','yesterday')
f_new.write(line)
f.close()
f_new.close()
如果把第四行的‘昨日’改成英文字体,如果替换的是中文,则对应新的文本在对于的位置是个乱码,应该是没法写入中文。
f=open('/Users/zhangxiukang/Desktop/hello world.rtf','r',encoding='utf-8')
f_new=open('/Users/zhangxiukang/Desktop/hello.txt','w',encoding='utf-8')
for line in f:
if 'Yesterday' in line:
line=line.replace('Yesterday','昨日')
f_new.write(line)
f.close()
f_new.close()
如果逐个打印出文本,则出现英文和ascii码混合的一堆东西。
f=open('/Users/zhangxiukang/Desktop/hello world.rtf','r',encoding='utf-8')
f_new=open('/Users/zhangxiukang/Desktop/hello.txt','w',encoding='utf-8')
for line in f:
if 'Yesterday' in line:
line=line.replace('Yesterday','昨日')
f_new.write(line)
print(line)
f.close()
f_new.close()
打印内容:
\f0\fs24 \cf2 \cb3 \expnd0\expndtw0\kerning0
Somehow, it seems the love I knew was always the most destructive kind
\f1 \'b2\'bb\'d6\'aa\'ce\'aa\'ba\'ce\'a3\'ac\'ce\'d2\'be\'ad\'c0\'fa\'b5\'c4\'b0\'ae\'c7\'e9\'d7\'dc\'ca\'c7\'d7\'ee\'be\'df\'bb\'d9\'c3\'f0\'d0\'d4\'b5\'c4\'b5\'c4\'c4\'c7\'d6\'d6
\f0 昨日 when I was young
\f1 \'d7\'f2\'c8\'d5\'b5\'b1\'ce\'d2\'c4\'ea\'c9\'d9\'c7\'e1\'bf\'f1
\f0 The taste of life was sweet
我在anaconda上测试也是这问题,但是以上这些代码在iPad上可以正常运行,编码utf-8 我也设置了,所以我觉得应该是电脑上设置问题,哪位大神看到了希望指导一下!万分感谢
|