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レシピを使用することをお勧めします。csvUnicodeWritercsv

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 に答える