簡體   English   中英

Python:編寫列表列表時的ascii編解碼器u'\\ xe8

[英]Python: ascii codec u'\xe8 when writing list of lists

我試圖將列表列表寫入文件,當我嘗試將列表列表轉換為字符串時遇到編碼錯誤。

值包含一個列表列表,如下所示:

[[fsdé,fsdqè,fdsq],[foo1,foo2,foo3]]

這是我的代碼:

f = open('workfile', 'w')
f.write("\n".join("\t".join(map(str,l)) for l in value))

這是錯誤:

Traceback (most recent call last):

  File "<string>", line 1, in <module>

  File "package_list_script.py", line 23, in craft_json

    f.write("\n".join("\t".join(map(str,l)) for l in value))

  File "package_list_script.py", line 23, in <genexpr>

    f.write("\n".join("\t".join(map(str,l)) for l in value))

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 4: ordinal not in range(128)

with io.open("somefile.txt", "w") as fout: fout.write(u"\n".join("\t".join(map(str,l)) for l in value))

使用Python 3模塊並在字符串前面指定“ u”! 阿門

好的,您需要連接包含重音符號的字符串 ,然后將它們寫入文件。 當您嘗試使用str轉換它們並獲得UnicodeEncodeError我假設l是unicode列表的列表。

您可以簡單地嘗試以unicode處理所有內容:

f.write((u"\n".join(u"\t".join(l) for l in value)).encode(encoding))

其中編碼可以是latin1utf8cp1252或您要用於文件的編碼。

另外,您可以編碼單個字符串:

f.write("\n".join("\t".join(map((lambda x: x.encode('utf8')), l)) for l in value))

Python 3將為您完成此任務。

在Python 2中,您可以像這樣使用Python 3的io模塊:

with io.open("somefile.txt", "w") as fout: fout.write(u"\N{EURO SIGN}")

您可以顯式地指定io.open encoding=... ,或者像我在這里所做的那樣,我依賴於默認值locale.getpreferredencoding()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM