这是我用来替换文本文件中的特殊字符并将它们连接到单个文件的代码。
# -*- 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!"
总是返回“未找到!” 证明这些字符没有被读取。
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)
我被困在这里。有什么建议么??欢迎所有答案!