我从一个目录中读取了一个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')发布于 2014-12-31 08:52:11
我想你的意思是解码
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",而á又是所有的case
发布于 2016-09-19 23:17:28
在python3中,您可以使用:
res = [tuple(map(lambda x: x.encode(encoding), tup)) for tup in list_tuples]示例:
list_tuples = [('mucho','fácil'), ('\u2019', 't')]
res = [tuple(map(lambda x: x.encode('utf-8'), tup)) for tup in list_tuples]结果:
[(b'mucho', b'f\xc3\xa1cil'), (b'\xe2\x80\x99', b't')]https://stackoverflow.com/questions/27714750
复制相似问题