我的数据在列表中。我对数据进行了标记。数据包含非字母(例如,?、.、!)。
我想从下面的列表中删除非字母(例如?、.、!)。
[['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/