python - 如果出现,则在分隔符上拆分列表的字符串

标签 python list loops unicode

我从网页(在 codecademy.com 的一个项目中)获取 HTML 代码。 提取结果是一个文本。我把它分成了一个列表。

问题:某些结果包含 Unicode 字符,我想从它们出现的字符串中删除这些字符。

['Normal String', 'Company\xc2\xae', 'againnormal', '\xc2\xb7']

结果应该是这样的:

['Normal String', 'Company', 'againnormal', '']

或者理想情况下是这样的

['Normal String', 'Company', 'againnormal']

最佳答案

怎么样

>>> stuff = ['Normal String', 'Company\xc2\xae', 'againnormal', '\xc2\xb7']
>>> filter(None, [x.decode('utf8').encode('ascii', 'ignore') for x in stuff])
['Normal String', 'Company', 'againnormal']

或者使用正则表达式

>>> import re
>>> filter(None, [re.sub(r'[^\x00-\x7F]+', '', x) for x in stuff])
['Normal String', 'Company', 'againnormal']

没有列表理解:

keep = []
for item in stuff:
    item = item.decode('utf8').encode('ascii', 'ignore')
    if item:
        keep.append(item)

关于python - 如果出现,则在分隔符上拆分列表的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40255374/

相关文章:

python - 在Kivy的GridLayout中设置网格列宽度?

list - 如何处理方案列表中特定范围的数字?

c# - 获取由元组列表的第一个值组成的数组

原生数据容器与 Pandas DataFrame 的 Python 性能对比

python - pickle 的字节数据如何取消 pickle ?

python - 从大型结构化文本文件中提取信息

python - 如何使用 python 访问爱思华宝服务器上的 "Documents"部分?

c# - AddRange 抛出 null 异常

Python 递归列表( pop 与 [ ] )

Python 3.0 : Looping list index that is "out of range"