我编写了一个 Python 脚本,用于处理以 UTF-8 编码的非 ascii 字符的 CSV 文件。但是输出的编码被破坏了。因此,从输入中:
"d\xc4\x9bjin hornictv\xc3\xad"
我在输出中得到这个:
"d\xe2\x99\xafjin hornictv\xc2\xa9\xc6\xaf"
你能建议编码错误可能来自哪里吗?你以前见过类似的行为吗?
编辑:我正在使用带有文档中特色类的csv
标准库。我使用 Python 2.6.6 版。UnicodeWriter
编辑2:重现行为的代码:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import csv
from pymarc import MARCReader # The pymarc package available PyPI: http://pypi.python.org/pypi/pymarc/2.71
from UnicodeWriter import UnicodeWriter # The UnicodeWriter from: http://docs.python.org/library/csv.html
def getRow(tag, record):
if record[tag].is_control_field():
row = [tag, record[tag].value()]
else:
row = [tag] + record[tag].subfields
return row
inputFile = open("input.mrc", "r")
outputFile = open("output.csv", "wb")
reader = MARCReader(inputFile, to_unicode = True)
writer = UnicodeWriter(outputFile, delimiter = ",", quoting = csv.QUOTE_MINIMAL)
for record in reader:
if bool(record["001"]):
tags = [field.tag for field in record.get_fields()]
tags.sort()
for tag in tags:
writer.writerow(getRow(tag, record))
inputFile.close()
outputFile.close()
输入数据可在此处获得(大文件)。