【问题标题】:Converting unicode list to string of list将 unicode 列表转换为列表字符串
【发布时间】:2015-09-18 13:09:35
【问题描述】:

我有一个 unicode 列表。现在我需要将其转换为列表字符串列表。我怎样才能做到这一点?

listoflist = [
    [
        u'keep', u'see', u'recover', u'try', u'cry', u'say', u'seem',
        u'come', u'saw', u'have', u'be', u'begin', u'fell', u'wait',
        u'come', u'wait', u'be', u'retire', u'be'
    ],
    [
        u'make', u'let', u'forget', u'forgive', u'punish', u'take', u'be',
        u'take', u'forget', u'come', u'think', u'say', u'be', u'be', u'say',
        u'think', u'jump', u'poke', u'come', u'be', u'have', u'try', u'come',
        u'turn', u'approach', u'be', u'meet', u'try', u'run', u'boast',
        u'bring', u'satisfy', u'use', u'be', u'leave', u'be', u'do', u'say',
        u'bristle'
    ]
]

我尝试使用ast

import ast
d = []
for i in range(0,50):
    d.append([item.encode('ascii') for item in ast.literal_eval(listoflist)])

但我收到以下错误。

    raise ValueError('malformed string')
ValueError: malformed string

欢迎采用不同的方法。

【问题讨论】:

  • 您使用的是 Python 2 吗?您应该总是在 Unicode 问题中提及 Python 版本,因为在 Python 3 中处理 Unicode 的方式与在 Python 2 中的处理方式完全不同。
  • @PM2Ring 我明白了。是的,我使用的是 python 版本 2。

标签: python list unicode python-2.x


【解决方案1】:

这将返回 d 作为一个包含 ascii 字符串而不是 unicode 的数组的数组。

# Iterate through each list in listoflist
# Then iterate through each unicode string in listoflist

d = [[s.encode('ascii') for s in list] for list in listoflist]

正如@pm-2ring 提到的,如果您想忽略无法转换为asciiunicode 字符串,也可以使用s.encode('ascii', 'ignore')

获取我们使用的每个列表。 for list in listoflist

获取我们使用的每个 unicode 字符串。 for s in list.

然后转换我们使用s.encode('ascii')

【讨论】:

  • @KevinOelen:另外,如果您希望它忽略无法转换为 ASCII 的 Unicode 内容,您可以使用x.encode('ascii', 'ignore')。有关详细信息,请参阅str.encode 的文档。
【解决方案2】:

如果您想让您的代码易于理解,请执行此操作

for l in listoflist:
    d_temp = []
    for s in l:
        d_temp.append(s.encode('ascii'))
    d.append(d_temp)

【讨论】:

  • 这个比较容易理解。但似乎遍历列表列表是更节省时间的方式。谢谢顺便说一句。
猜你喜欢
  • 2014-09-30
  • 1970-01-01
  • 1970-01-01
  • 2012-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-29
  • 1970-01-01
相关资源
最近更新 更多