我正在尝试删除文件夹中所有编码文件中的所有重音..我已经成功地构建了文件列表,问题是当我尝试使用unicodedata进行标准化时,我得到了错误:** Traceback (最近一次调用):文件"/usr/lib/gedit-2/plugins/pythonconsole/console.py",第336行,在self.namespace文件的__run执行命令中"",第2行,在UnicodeDecodeError中:'utf8‘编解码器无法解码位置25中的字节0xf3 :无效的继续字节**
if options.remove_nonascii:
nERROR = 0
print _("# Removing all acentuation from coding files in %s") % (options.folder)
exts = ('.f90', '.f', '.cpp', '.c', '.hpp', '.h', '.py'); files=set()
for dirpath, dirnames, filenames in os.walk(options.folder):
for filename in (f for f in filenames if f.endswith(exts)):
files.add(os.path.join(dirpath,filename))
for i in range(len(files)):
f = files.pop() ;
os.rename(f,f+'.BACK')
with open(f,'w') as File:
for line in open(f+'.BACK').readlines():
try:
newLine = unicodedata.normalize('NFKD',unicode(line)).encode('ascii','ignore')
File.write(newLine)
except UnicodeDecodeError:
nERROR +=1
print "ERROR n %i - Could not remove from Line: %i" % (nERROR,i)
newLine = line
File.write(newLine)发布于 2011-02-09 00:33:39
看起来该文件可能是用cp1252编解码器编码的:
In [18]: print('\xf3'.decode('cp1252'))
óunicode(line)失败是因为unicode尝试使用utf-8编解码器来解码line,因此出现了错误UnicodeDecodeError: 'utf8' codec can't decode...。
您可以先尝试使用cp1252解码line,如果失败,请尝试utf-8:
if options.remove_nonascii:
nERROR = 0
print _("# Removing all acentuation from coding files in %s") % (options.folder)
exts = ('.f90', '.f', '.cpp', '.c', '.hpp', '.h', '.py'); files=set()
for dirpath, dirnames, filenames in os.walk(options.folder):
for filename in (f for f in filenames if f.endswith(exts)):
files.add(os.path.join(dirpath,filename))
for i,f in enumerate(files):
os.rename(f,f+'.BACK')
with open(f,'w') as fout:
with open(f+'.BACK','r') as fin:
for line fin:
try:
try:
line=line.decode('cp1252')
except UnicodeDecodeError:
line=line.decode('utf-8')
# If this still raises an UnicodeDecodeError, let the outer
# except block handle it
newLine = unicodedata.normalize('NFKD',line).encode('ascii','ignore')
fout.write(newLine)
except UnicodeDecodeError:
nERROR +=1
print "ERROR n %i - Could not remove from Line: %i" % (nERROR,i)
newLine = line
fout.write(newLine)顺便说一下,
unicodedata.normalize('NFKD',line).encode('ascii','ignore')有点危险。例如,它完全删除了u‘²’和一些引号:
In [23]: unicodedata.normalize('NFKD',u'ß').encode('ascii','ignore')
Out[23]: ''
In [24]: unicodedata.normalize('NFKD',u'‘’“”').encode('ascii','ignore')
Out[24]: ''如果这是一个问题,那么使用unidecode module
In [25]: import unidecode
In [28]: print(unidecode.unidecode(u'‘’“”ß'))
''""ss发布于 2011-02-09 00:12:07
您可能希望在使用unicode(line)时指定编码,例如unicode(line,'utf-8')
如果您不知道,sys.getfilesystemencoding()可能是您的朋友。
https://stackoverflow.com/questions/4935347
复制相似问题