我在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)在旁注中,我应该如何报告这个Python错误,特定的shift_jis字符似乎无法正确解码?
答案 0 :(得分:3)
通常,您可以使用errors='ignore'
跳过无效字符:
list_of_unicode_row_values = [str.decode('shift_jis', errors='ignore') for str in list_of_row_values]
这导致list_of_unicode_row_values
中的以下条目:
日付
直流電流計測
直流電流計測
但是,在您的特定情况下,您使用了错误的编码。 Python的shift_jis
编码符合JIS X 0208标准,而字符①存在于较新的JIS X 0213标准中。要使用后者,只需使用shift_jisx0213
编码:
list_of_unicode_row_values = [str.decode('shift_jisx0213') for str in list_of_row_values]
您将收到以下条目:
日付
直流電流計測①
直流電流計測②
正如所料。