python - 用python编码元组列表?

标签 python python-2.7 encoding io character-encoding

我正在从一个目录中读取一个 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/

相关文章:

google-app-engine - ndb.StructuredProperty 不保存 key ?

python - 设置两个 matplotlib imshow 图具有相同的颜色图比例

python - 这段代码 : %(var)s ? Python 可能是什么?

python - Cython 的意外输出和返回值

Python 反转元组的某些部分

video - ffmpeg:两步编码是否解决了视频转换过程中的问题?

ruby - open-uri 从以 iso-8859 编码的网页返回 ASCII-8BIT

sql - UPPER() 不适用于 PostgreSQL 8.2 数据库中的西里尔符号

python - 如何对二进制值数组的行进行排序,就好像它们是长二进制数一样?

python - Reportlab - 表格扩展到多个框架和页面