2017-07-29 9 views
1

私は他の回答を見てきました、そして、彼らが推奨されるものを行っている:WindowsコマンドラインでのPythonエンコーディング:Chcp 932が機能しません。

1. Changed system locale to Japanese 
2. Chcp 932 (Japanese) 
3. Python file saved as UTF-8 
4. All inputs are subject to the unicode(input, 'utf-8') function as seen below. 

注:私はまた、CHCP 65001を使用して試してみたが、これはどちらか動作しません。

日本語のCSVファイルを読み込もうとしていますが、次のエラーが引き続き発生します。

Traceback (most recent call last): 
... 
... 
UnicodeEncodeError: 'cp932' codec can't encode character u'\ufeff' in position 0: illegal multibyte sequence 

私のコードとサンプルファイルの内容:

def setFood(self): 
     reader = self.unicode_csv_reader(open("food.csv")) 
     aDict = {} 
     for field1, field2 in reader: 
      if field2 not in aDict.keys(): 
       aDict[field2] = [field1] 
      else: 
       aDict[field2] += [field1] 
     return aDict 

    def unicode_csv_reader(self, utf8_data, dialect=csv.excel, **kwargs): 
     reader = csv.reader(utf8_data, dialect=dialect, **kwargs) 
     for row in reader: 
      yield [unicode(cell, 'utf-8') for cell in row] 

    def recFood(self, inp): 
     print inp 
     for key in self.foodDict.keys(): 
      for value in self.foodDict[key]: 
       print(key) 
       print(value) 

サンプルCSV

ヤクルト,飲み物 
カキフライ,洋食 
エビフライ,洋食 
豚カツ,洋食 

答えて

2

The example at the bottom of the Python 2.7 csv module documentationが何をしたいですが、エンコーディングにutf-8-sigを使用しています。 \ufeffはバイトオーダーマーク(BOM)文字で、エンコーディングがあればそれを正しく処理します。

には、Windowsコンソールで印刷するための日本語システムロケールが必要です。より良い、Unicode APIを使用してコンソールで印刷するPython 3.6に切り替える...必要なのは、日本語をサポートするフォントです。 Python 3のcsvモジュールもUnicode対応であり、よりうまく動作します。

import csv, codecs 

class UTF8Recoder: 
    """ 
    Iterator that reads an encoded stream and reencodes the input to UTF-8 
    """ 
    def __init__(self, f, encoding): 
     self.reader = codecs.getreader(encoding)(f) 

    def __iter__(self): 
     return self 

    def next(self): 
     return self.reader.next().encode("utf-8") 

class UnicodeReader: 
    """ 
    A CSV reader which will iterate over lines in the CSV file "f", 
    which is encoded in the given encoding. 
    """ 

    def __init__(self, f, dialect=csv.excel, encoding="utf-8-sig", **kwds): 
     f = UTF8Recoder(f, encoding) 
     self.reader = csv.reader(f, dialect=dialect, **kwds) 

    def next(self): 
     row = self.reader.next() 
     return [unicode(s, "utf-8") for s in row] 

    def __iter__(self): 
     return self 

with open('food.csv','rb') as f: 
    r = UnicodeReader(f) 
    for key,value in r: 
     print key,value 
ヤクルト 飲み物 
カキフライ 洋食 
エビフライ 洋食 
豚カツ 洋食 
関連する問題