以下是我使用的代码,用于替换文本文件中的特殊字符并将它们连接成一个单独的文件。
# -*- coding: utf-8 -*-
import os
import codecs
dirpath = "C:\\Users\\user\\path\\to\\textfiles"
filenames = os.listdir(dirpath)
with codecs.open(r'C:\Users\user\path\to\output.txt', 'w', encoding='utf8') as outfile:
for fname in filenames:
currentfile = dirpath+"\\"+fname
with codecs.open(currentfile, encoding='utf8') as infile:
#print currentfile
outfile.write(fname)
outfile.write('\n')
outfile.write('\n')
for line in infile:
line = line.replace(u"´ı", "i")
line = line.replace(u"ï¬", "fi")
line = line.replace(u"fl", "fl")
outfile.write (line)
line.replace
的第一个使用是正确的,而其他的则不行(这是有道理的),由于没有生成错误,所以我认为可能存在“可见性”问题(如果这是术语的话)。所以我做了这个:
import codecs
currentfile = 'textfile.txt'
with codecs.open('C:\\Users\\user\\path\\to\\output2.txt', 'w', encoding='utf-8') as outfile:
with open(currentfile) as infile:
for line in infile:
if "ï¬" not in line: print "not found!"
这段代码总是返回“not found!”,证明这些字符没有被读取。
当在第一个脚本中改为with codecs.open('C:\Users\user\path\to\output.txt', 'w', encoding='utf-8') as outfile:
时,我会得到以下错误:
Traceback (most recent call last):
File C:\\path\\to\\concat.py, line 30, in <module>
outfile.write(line)
File C:\\Python27\\codecs.py, line 691, in write
return self.writer.write(data)
File C:\\Python27\\codecs.py, line 351, in write
data, consumed = self.encode(object, self.errors)
Unicode DecodeError: 'ascii' codec can't decode byte 0xe7 in position 0: ordinal
not in range (128)
由于我在Python方面经验不足,无法通过已有的不同来源解决问题:Python文档(1,2)和StackOverflow相关问题(1,2),我现在陷入了困境。有什么建议吗?欢迎所有答案!