PythonでCSVファイルの入力をもとにJSONファイルの文字置換を行った際に以下のようなエラーが生じます
どのようにすれば解決できるでしょうか?
Traceback (most recent call last): File "replace_text.py", line 28, in <module> for row in spamreader: File "replace_text.py", line 18, in unicode_csv_reader for row in csv_reader: File "replace_text.py", line 24, in utf_8_encoder yield line.encode('utf-8') UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)
行っていることは
①JSON(TopoJSON)ファイルの中からCSVファイルの1列目と同じ文字列を見つける(札幌市、など)
②見つけた文字列をCSVファイルの2列目の文字列に置換する(札幌市の場合は、id011002)
③全ての文字列を置換し終えたJSON(TopoJSON)ファイルを出力
ということです
使用しているpythonのプログラムは以下になります。
#coding:utf-8 ''' Created on 2014/03/27 @author: hitsuji ''' import csv # 置換リストをCSVファイルで読み込む words_filename = 'replace_words' document_in = 'yokohama.topojson' document_out = 'yokohama_topo_out.json' words = [] def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs): # csv.py doesn't do Unicode; encode temporarily as UTF-8: csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),dialect=dialect, **kwargs) for row in csv_reader: # decode UTF-8 back to Unicode, cell by cell: yield [unicode(cell, 'utf-8') for cell in row] def utf_8_encoder(unicode_csv_data): for line in unicode_csv_data: yield line.encode('utf-8') with open(words_filename + '.csv', 'rU') as csvfile: spamreader = unicode_csv_reader(csvfile, dialect=csv.excel) for row in spamreader: words.append(row) text = u"" with open(document_in, 'rU') as docfile: tmpdoc = docfile.read() docfile.close() text = tmpdoc.encode('utf-8') for pair in words: text = text.replace(pair[0], pair[1]) with open(document_out, 'w') as f: f.write(text) f.close()
それぞれのファイルの中身は以下のようになっています。
☆JSON(TopoJSON)ファイルの中身 (軽く1万文字は超えますが、省略します)
{"type":"Topology","objects":{"hokkaido":{"type":"GeometryCollection","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG::4612"}},"geometries":[ {"type":"Polygon","properties":{"name":"札幌市"},"arcs":[[0,1,2,3,4,5]]}, {"type":"Polygon","properties":{"name":"旭川市"},"arcs":[[6,-6,7,8,9,10]]}, {"type":"Polygon","properties":{"name":"小樽市"},"arcs":[[11,-1,-7,12,13]]}, {"type":"Polygon","properties":{"name":"函館市"},"arcs":[[14,15,16,-2,-12,17]]}・・・
☆CSVファイルの中身 (200ほどこのような列が続きます)
1列目 2列目 札幌市 id011002 函館市 id012025 小樽市 id012033 旭川市 id012041 ・ ・ ・
どなたかこの解決方法をご存知の方がおりましたら、アドバイスをお願いいたします。
回答2件
あなたの回答
tips
プレビュー