Python - 解码列表中的 utf-8 列表(解码整个列表对象)
Python - Decode utf-8 list in lists (decode entire list objects)
假设我有一个包含多个列表的列表,例如:
l = [['a'],['a','b'],['c'],['d',['a','b'],'f']]
有了这个:
l = [x.decode('UTF8') for x in l]
可能会出现错误:列表对象没有属性 'decode'
("l" 从标记化文本创建的列表,它的每个单词都是列表对象。尝试了很多解决方案来克服解码困难,但仍然无法打印非 ascii 字符)
with open(path, "r") as myfile:
text=myfile.read()
text = word_tokenize(text)
d = [[item] if not isinstance(item, list) else item for item in text]
arr = sum(([[x[0] for x in g]] if k else list(g)
for k, g in groupby(d, key=lambda x: x[0][0].isupper())),
[])
arr = [x.decode('UTF8') for x in arr]
INPUT(我的文本文件):
Çanakkale çok güzel bir şehirdir. Çok beğendik.
输出:
[[u'\xc7anakkale'], [u'\xe7ok'], [u'g\xfczel'], [u'bir'], [u'\u015fehirdir'], [u'.']. [u'\xe7ok'], [u'be\u011fendik'], [u'.']]
我想要的输出是列表,但与我的输入格式完全一样。
您可以使用简单的递归函数进行解码:
l1 = [['a'],['a','b'],['c'],['d',['a','b'],'f']]
def decode(l):
if isinstance(l, list):
return [decode(x) for x in l]
else:
return l.decode('utf-8')
decode(l1) # [[u'a'], [u'a', u'b'], [u'c'], [u'd', [u'a', u'b'], u'f']]
首先,您认为您遇到的问题是您正在打印整个列表(您没有在您的问题中包括那部分,所以我不得不猜测)- Python 正在打印数据的安全表示。对你来说,这意味着它表明你有 Unicode 字符串(因此 u''
)并且它显示非 ASCII 字符的 Unicode 点十六进制值。
如果您要打印列表的单个部分,那么您会得到您期望的结果。
即
>>> print arr[0][0]
Çanakkale
如果你想打印所有的值,你需要一个 for 循环:
for x in arr:
for y in x:
print y
您还通过手动解码代码深处的数据引入了不必要的复杂性 - 相反,您应该解码输入的数据。
您似乎正在使用 Python 2.x(通过 u'' 前缀),因此请使用 io
模块在您阅读文本数据时对其进行解码:
import io
with io.open(path, "r", encoding="utf-8") as myfile:
text=myfile.read()
现在您可以删除 arr = [x.decode('UTF8') for x in arr]
行。
假设我有一个包含多个列表的列表,例如:
l = [['a'],['a','b'],['c'],['d',['a','b'],'f']]
有了这个:
l = [x.decode('UTF8') for x in l]
可能会出现错误:列表对象没有属性 'decode'
("l" 从标记化文本创建的列表,它的每个单词都是列表对象。尝试了很多解决方案来克服解码困难,但仍然无法打印非 ascii 字符)
with open(path, "r") as myfile:
text=myfile.read()
text = word_tokenize(text)
d = [[item] if not isinstance(item, list) else item for item in text]
arr = sum(([[x[0] for x in g]] if k else list(g)
for k, g in groupby(d, key=lambda x: x[0][0].isupper())),
[])
arr = [x.decode('UTF8') for x in arr]
INPUT(我的文本文件):
Çanakkale çok güzel bir şehirdir. Çok beğendik.
输出:
[[u'\xc7anakkale'], [u'\xe7ok'], [u'g\xfczel'], [u'bir'], [u'\u015fehirdir'], [u'.']. [u'\xe7ok'], [u'be\u011fendik'], [u'.']]
我想要的输出是列表,但与我的输入格式完全一样。
您可以使用简单的递归函数进行解码:
l1 = [['a'],['a','b'],['c'],['d',['a','b'],'f']]
def decode(l):
if isinstance(l, list):
return [decode(x) for x in l]
else:
return l.decode('utf-8')
decode(l1) # [[u'a'], [u'a', u'b'], [u'c'], [u'd', [u'a', u'b'], u'f']]
首先,您认为您遇到的问题是您正在打印整个列表(您没有在您的问题中包括那部分,所以我不得不猜测)- Python 正在打印数据的安全表示。对你来说,这意味着它表明你有 Unicode 字符串(因此 u''
)并且它显示非 ASCII 字符的 Unicode 点十六进制值。
如果您要打印列表的单个部分,那么您会得到您期望的结果。
即
>>> print arr[0][0]
Çanakkale
如果你想打印所有的值,你需要一个 for 循环:
for x in arr:
for y in x:
print y
您还通过手动解码代码深处的数据引入了不必要的复杂性 - 相反,您应该解码输入的数据。
您似乎正在使用 Python 2.x(通过 u'' 前缀),因此请使用 io
模块在您阅读文本数据时对其进行解码:
import io
with io.open(path, "r", encoding="utf-8") as myfile:
text=myfile.read()
现在您可以删除 arr = [x.decode('UTF8') for x in arr]
行。