[英]Encoding (UTF-8) issue
我想從列表中寫入文本。 但是編碼不起作用並且像位一樣寫入。
with open('freq.txt', 'w') as f:
for item in freq:
f.write("%s\n" % item.encode("utf-8"))
輸出:
b'okul'
b'y\xc4\xb1l\xc4\xb1'
預期:
okul
yılı
如果您使用的是Python3,則可以在open的調用中聲明所需的編碼:
with open('freq.txt', 'w', encoding='utf-8') as f:
for item in freq:
f.write("%s\n" % item)
如果不提供編碼,則默認為locale.getpreferredencoding()返回的編碼。
您的代碼的問題是'%s\\n' % item.encode('utf-8')
將item
編碼為字節,但是字符串格式化操作隱式調用了字節上的str
,這導致使用了字節的repr構造字符串。
>>> s = 'yılı'
>>> bs = s.encode('utf-8')
>>> bs
b'y\xc4\xb1l\xc4\xb1'
>>> # See how the "b" is *inside* the string.
>>> '%s' % bs
"b'y\\xc4\\xb1l\\xc4\\xb1'"
將格式字符串設置為bytes
文字可避免此問題
>>> b'%s' % bs
b'y\xc4\xb1l\xc4\xb1'
但由於無法將字節寫入以文本模式打開的文件,因此寫入文件將失敗。 如果您真的想手動編碼,則必須執行以下操作:
# Open the file in binary mode.
with open('freq.txt', 'wb') as f:
for item in freq:
# Encode the entire string before writing to the file.
f.write(("%s\n" % item).encode('utf-8'))
import codecs
with codecs.open("lol", "w", "utf-8") as file:
file.write('Okul')
file.write('yılı')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.