python - 从 python 列表中的标记中删除非字母

标签 python python-2.7

我的数据在列表中。我对数据进行了标记。数据包含非字母(例如,?、.、!)。

我想从下面的列表中删除非字母(例如?、.、!)。

[['comfortable',
  'questions?',
  'menu',
  'items!',
  'time',
  'lived',
  'there,',
  'could',
  'easily',
  'direct',
  'people',
  'appropriate',
  'menu',
  'choices',
  'given',
  'allergies.'],
 ['.',
  'sure',
  'giving',
  'wheat',
  'fiction',
  'free',
  'foodthis',
  'place',
  'clean.']]

输出应如下所示:

[['comfortable',
  'questions',
  'menu',
  'items',
  'time',
  'lived',
  'there,',
  'could',
  'easily',
  'direct',
  'people',
  'appropriate',
  'menu',
  'choices',
  'given',
  'allergies'],
 ['sure',
  'giving',
  'wheat',
  'fiction',
  'free',
  'foodthis',
  'place',
  'clean']]

我尝试了下面的代码(不起作用):

import re 
tokens = [re.sub(r'[^A-Za-z0-9]+', '', x) for x in texts] 

有什么建议吗?

最佳答案

您的正则表达式方法不起作用,因为您拥有的是列表的列表,因此您试图将内部列表传递给 re.sub

您还应该迭代内部列表,然后使用您的 re.sub 。示例-

>>> tokens = [[y for y in (re.sub(r'[^A-Za-z0-9]+', '', x) for x in sublst) if y] for sublst in texts]
>>> pprint.pprint(tokens)
[['comfortable',
  'questions',
  'menu',
  'items',
  'time',
  'lived',
  'there',
  'could',
  'easily',
  'direct',
  'people',
  'appropriate',
  'menu',
  'choices',
  'given',
  'allergies'],
 ['sure', 'giving', 'wheat', 'fiction', 'free', 'foodthis', 'place', 'clean']]

关于python - 从 python 列表中的标记中删除非字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32571686/

相关文章:

python - 我可以在 Google 的 ortools 包中提供一个带有 BFS 的求解器来启动吗?

python - 如何在 python 中处理非常大的文件?

python - 分组装箱

python - PySpark 按值分解键并保留 LDA 模型的重复项

python - 如何从进程或线程实例返回值?

python - 在 for 循环中附加 Pandas 数据帧会导致 ValueError

python - 导入 pyqtgraph 时 python 2.7 中的段错误(核心转储)

python - 获取基于特定项目的先前值

Python PyQt 进度条忙

python - 调用setup.py中的函数(使用tox)