我在 Linux 上使用 Python 2.6。我正在加载一个 shift_jis(日语)编码的 .csv 文件。我正在读取标题,并进行正则表达式替换以翻译一些值,然后将文件写回 shift_jis。我在文件中的一个字符上遇到了 UnicodeDecodeError,①,根据http://www.rikai.com/library/kanjitables/kanji_codes.sjis.shtml ,它应该是一个有效字符。其他日文字符解码良好。
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 错误?