2013-04-04 57 views
0

我想寫Unicode數據(實際數據中包含德語字符)的文件,但我得到的錯誤:錯誤而寫Unicode數據到文件

Traceback (most recent call last): 
    File "C:\Python27\extract_osm_road_nw.py", line 76, in <module> 
    file.write(str(list_way_id[index][2][i][1])) 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xdf' in position 12: ordinal not in range(128) 

的代碼是:

## writing the data in a file 
## The data format is: 
## A list of: [tuple(way ref id,list[tuple(node id, lat, long)],list[tuple(key,value)]),.....] 
## For example: [(u'72439830', [(u'298094414', u'52.4626304', u'10.5579578'), (u'860126050', u'52.4626762', u'10.5576574')], [(u'name', u'General-BeckStra\xdfe')]),.....] 

with codecs.open("extracted_osm_file.csv", "w", encoding="utf-8") as file: 
    for index in range(len(list_way_id)): 
     file.write("Way ID Ref No: ") 
     file.write(str(list_way_id[index][0]))## points to the way id ref no 
     file.write("\n") 
     file.write("Node reference id, latitude, longitude: ") 
     file.write("\n") 
     for i in range(len(list_way_id[index][1])): 
      file.write(str(list_way_id[index][1][i][0])) 
      file.write(",") 
      file.write(str(list_way_id[index][1][i][1])) 
      file.write(",") 
      file.write(str(list_way_id[index][1][i][2])) 
      file.write("\n") 
     for i in range(len(list_way_id[index][2])): 
      file.write(str(list_way_id[index][2][i][0])) 
      file.write(",") 
      file.write(str(list_way_id[index][2][i][1])) 
      file.write("\n") 
    file.close() 
+0

字符串: 「一般-BeckStraße」 轉換爲Unicode:u'General-BeckStra \ xdfe」,創造了錯誤。 – tanzil 2013-04-04 14:43:48

+0

http://nedbatchelder.com/text/unipain.html – 2013-04-04 14:43:55

回答

0

刪除對str()的呼叫。這些嘗試使用默認的ASCII編碼將您必須的Unicode數據轉換爲字節碼。

你可能想在這裏使用csv模塊,並保存自己不必編寫所有的逗號的悲痛,但如果你不能,至少使用循環正常:

with codecs.open("extracted_osm_file.csv", "w", encoding="utf-8") as fileobj: 
    for line in list_way_id: 
     fileobj.write(u'Way ID Ref No: {}\n'.format(line[0])) 
     fileobj.write(u'Node reference id, latitude, longitude: \n') 
     fileobj.write(u'\n'.join([u','.join(subentry) 
      for entry in line[1:] for subentry in entry])) 

其中,爲您的部分例如,會寫:

Way ID Ref No: 72439830 
Node reference id, latitude, longitude: 
298094414,52.4626304,10.5579578 
860126050,52.4626762,10.5576574 
name,General-BeckStra\xc3\x9fe 
+0

非常感謝str()在創建問題 – tanzil 2013-04-04 14:53:47

+0

請參見['csv'模塊文檔](http://docs.python.org/2/library/ csv.html)如何使用該模塊;你必須自己編碼。 – 2013-04-04 15:02:01