3

我编写了一个 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()

输入数据可在此处获得(大文件)。

4

2 回答 2

2

似乎向构造函数添加force_utf8 = True参数MARCReader解决了这个问题:

reader = MARCReader(inputFile, to_unicode = True, force_utf8 = True)

根据对源代码的检查(通过inspect),它会执行以下操作:

string.decode("utf-8", "strict")
于 2011-01-25T15:05:43.123 回答
0

您可以尝试使用 UTF-8 编码打开文件:

import codecs
codecs.open('myfile.txt', encoding='utf8')
于 2011-01-25T13:43:16.287 回答