[英]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.