LinuxでPython 2.6を使用しています。shift_jis (日本語) でエンコードされた .csv ファイルを読み込んでいます。ヘッダーを読み込んで、正規表現の置換を行っていくつかの値を変換し、ファイルを shift_jis として書き戻しています。http://www.rikai.com/library/kanjitables/kanji_codes.sjis.shtmlによると、ファイル内の文字の 1 つ①で UnicodeDecodeError が発生しました。これは有効な文字である必要があります。他の日本語の文字は正常にデコードされます。
1) リスト内包表記で shift_jis を使用して文字列をデコードしています。この文字やその他の悪い文字を無視 (回避) したい場合はどうすればよいですか? これは、list_of_row_values で既に読み込まれた csv 値を含むコードです。
#! /usr/bin/python
# -*- coding: utf8 -*-
import csv
import re
with open('test.csv', 'wb') as output_file:
wr = csv.writer(output_file, delimiter=',', quoting=csv.QUOTE_NONE)
# the following corresponds to reading from a shift_jis encoded csv files "日付,直流電流計測①,直流電流計測②"
# 直流電流計測① is throwing an exception when decoded but it is a valid character according to
# http://www.rikai.com/library/kanjitables/kanji_codes.sjis.shtml
list_of_row_values = ['\x93\xfa\x95t', '\x92\xbc\x97\xac\x93d\x97\xac\x8cv\x91\xaa\x87@', '\x92\xbc\x97\xac\x93d\x97\xac\x8cv\x91\xaa\x87A']
# take away the last character in entry two, and three, and it would work
# but that means I know all the bad characters before hand
#list_of_row_values = ['\x93\xfa\x95t', '\x92\xbc\x97\xac\x93d\x97\xac\x8cv\x91\xaa', '\x92\xbc\x97\xac\x93d\x97\xac\x8cv\x91\xaa']
try:
list_of_unicode_row_values = [str.decode('shift_jis') for str in list_of_row_values]
except UnicodeDecodeError:
# Question: what if I want to just ignore the character that cannot be decoded and still get the list
# of "日付,直流電流計測,直流電流計測" as unicode?
# right now, list_of_unicode_row_values would remain undefined, and the next line will
# have a NameError
print 'UnicodeDecodeError'
pass
# do a regex explanation to translate one column heading value
list_of_translated_unicode_row_values = \
[re.sub('日付'.decode('utf-8'), 'Date Time', str) for str in list_of_unicode_row_values]
list_of_translated_row_values = [unicode_str.encode('shift_jis') for unicode_str in list_of_translated_unicode_row_values]
wr.writerow(list_of_translated_row_values)
2) 余談ですが、特定の shift_jis 文字が正しくデコードされていないように見えるという Python のバグをどのように報告すればよいですか?