我正在从一个目录中读取一个 utf-8 文本文件,然后我将读取的文本插入到一个列表中,并且我正在获取一些这样的元组:
l = [('mucho','fácil'),...,('yo','hola')]
当我在控制台上打印时,我有以下内容:
print l
('mucho','f\xc3\xa1cil'),...,('yo','hola')
所以我尝试了以下方法:
fixing_l = [x.encode('utf-8') for x in l]
当我尝试打印它时出现异常:
AttributeError: 'tuple' object has no attribute 'encode'
我怎样才能对字符串进行编码和修复并得到类似这样的东西?:
('mucho','fácil'),...,('yo','hola')
最佳答案
我想你的意思是解码
l = [('mucho','f\xc3\xa1cil'),...,('yo','hola')]
decoded = [[word.decode("utf8") for word in sets] for sets in l]
for words in decoded:
print u" ".join(words)
print 'f\xc3\xa1cil'.decode("utf8")
如果您打印它,您应该会看到正确的字符串。
由于您最初有一个正常的字节字符串,因此您需要 decode
它返回对象的 unicode 表示...在上面的例子中 u"\xe1"
真的只是<utf8 bytestring>"\xc3\xa1"
这反过来真的只是á
关于python - 用python编码元组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27714750/