python - 如何从列表中的项目中删除标点符号并将其另存为列表中的单独项目?

标签 python arrays list arraylist compression

我正在尝试将项目从一个列表压缩到另一个列表,我需要能够将标点符号保存为列表中的单独项目,因为如果我不这样做,“你”和“你;”在列表中保存为单独的项目。

例如原始列表是,

['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you;', 'ask', 'what '、'你'、'可以'、'做'、'为了'、'你的'、'国家!'、'这个'、'是'、'一个'、'引用'、'来自'、'JFK' , '谁', '是', 'a', '前任', '美国人', '总统。']

压缩列表目前是,

['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you;', 'ask', 'you ', '国家!', '这个', '是', '一个', '引用', '来自', 'JFK', '谁', '前任', '美国人', '总统。']

但我希望它在列表中将标点符号作为单独的项目。

我的预期输出是,

['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you', ';', 'ask' , '!', 'This', 'is', 'a', 'quote', 'from', 'JFK', 'who', 'former', 'American', 'President', '.']

最佳答案

你可以用regex来实现。

import re
a = ['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you;', 'ask', 'what', 'you', 'can', 'do', 'for', 'your', 'country!', 'This', 'is', 'a', 'quote', 'from', 'JFK', 'who', 'is', 'a', 'former', 'American', 'President.']
result = re.findall(r"[\w']+|[.,!?;]",' '.join(a))

输出

['Ask', 'not', 'what', 'your', 'country', 'can', 'do', 'for', 'you', ';', 'ask', 'what', 'you', 'can', 'do', 'for', 'your', 'country', '!', 'This', 'is', 'a', 'quote', 'from', 'JFK', 'who', 'is', 'a', 'former', 'American', 'President', '.']

这里有一个演示,可以帮助您了解更多关于 regex 的信息.

关于python - 如何从列表中的项目中删除标点符号并将其另存为列表中的单独项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37833260/

相关文章:

python - 在 Python 中将列表转换为字典

python - 如何将周期间分解为数据框中的多行

python - 如何使用 Matplotlib 制作具有光环效果的散点图?

c# - 从可枚举的内容构建 C# 列表

python - 我可以在 conftest.py 中定义 fixture 以外的函数吗

无法读取 C 中数组的值

c# - 检查 boolean 数组中的元素值 - C#

arrays - Swift4.2 如何将 "struct"构造的二维数组保存到UserDefaults中?

r - 计算列表中的值并创建包含计数的新列

c# - Mono 和 Linq 聚合方法。尝试将项目添加到新列表时出错