0

我正在尝试将 XML 文件转换为 CSV,但 XML 的编码(“ISO-8859-1”)显然包含 Python 用来写入行的 ascii 编解码器中没有的字符。

我得到错误:

Traceback (most recent call last):
  File "convert_folder_to_csv_PLAYER.py", line 139, in <module>
    xml2csv_PLAYER(filename)
  File "convert_folder_to_csv_PLAYER.py", line 121, in xml2csv_PLAYER
    fout.writerow(row)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 4: ordinal not in range(128)

我尝试按如下方式打开文件: dom1 = parse(input_filename.encode( "utf-8" ) )

并且我尝试在写入之前替换每行中的 \xe1 字符。有什么建议么?

4

1 回答 1

1

xml 解析器返回unicode对象。这是好事。问题是,csv模块无法处理它们。

unicode您可以在交给作者之前对 xml 解析器返回的每个字符串进行编码csv,但更好的办法是使用模块官方文档中的这个csvUnicodeWriter配方csv

import csv, codecs, cStringIO

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
    """

    def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([s.encode("utf-8") for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)
于 2011-01-17T21:42:49.177 回答