在Python中从XML写入CSV,编码错误

发布于 2024-10-12 15:00:53 字数 585 浏览 1 评论 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 字符。有什么建议吗?

I am trying to convert an XML file to CSV, but the encoding of the XML ("ISO-8859-1") apparently contains characters that are not in the ascii codec which Python uses to write rows.

I get the error:

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)

I have tried opening the file as follows:

dom1 = parse(input_filename.encode( "utf-8" ) )

and I have tried replacing the \xe1 character in each row before it is written. Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁吢 2024-10-19 15:00:53

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

您可以在将 xml 解析器返回的每个 unicode 字符串交给 csv 编写器之前进行编码,但更好的主意是使用此 csv UnicodeWriter Recipe 来自 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)

The xml parser returns unicode objects. That's a good thing. Thing is, csv module can't deal with them.

You could encode each unicode string returned by the xml parser before handing to the csv writer, but a better idea is to use this csv UnicodeWriter recipe from the official docs of the csv module:

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文