如何在一堆文本文件中用''替换所有'0xa0'字符?

alv*_*vas 4 python bash shell text utf-8

我一直在尝试在python中将一堆文本文件批量编辑为utf-8,并且此错误不断弹出.有没有办法在一些python scrips或bash命令中替换它们?我使用的代码:

writer = codecs.open(os.path.join(wrd, 'dict.en'), 'wtr', 'utf-8')
for infile in glob.glob(os.path.join(wrd,'*.txt')):
        print infile
        for line in open(infile):
                writer.write(line.encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

并得到了这些错误:

Traceback (most recent call last):
  File "dicting.py", line 30, in <module>
    writer.write(line2.encode('utf-8'))
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa0 in position 216: unexpected code byte
Run Code Online (Sandbox Code Playgroud)

nco*_*lan 11

好的,第一点:您的输出文件设置为自动编码写入其中的文本utf-8,因此encode('utf-8')在将参数传递给write()方法时不要包含显式方法调用.

所以首先要尝试的是在内循环中简单地使用以下内容:

writer.write(line)
Run Code Online (Sandbox Code Playgroud)

如果这不起作用,那么问题几乎肯定是,正如其他人所指出的那样,你没有正确解码你的输入文件.

猜测并假设您的输入文件已编码cp1252,您可以尝试在内循环中快速测试以下内容:

for line in codecs.open(infile, 'r', 'cp1252'):
    writer.write(line)
Run Code Online (Sandbox Code Playgroud)

小点:'wtr'是一个无意义的模式字符串(因为写访问意味着读访问).将其简化为'wt'或甚至只是'w'.