首页 > 解决方案 > 从 Python 中的列表元素中删除特定标点符号

问题描述

从一首歌曲的歌词中,我必须将每个单词作为元素获取,而元素中不包含任何逗号 (,)。例如:

她爱你,是的,是的,是的 她爱你,是的,是的,是的,是的 你以为你失去了你的爱 嗯,我昨天看到了她 她想的是你 她告诉我该说什么 她说她爱你你知道这不会是坏事

我确实将歌词拆分为列表元素,然后将它们变成小写字母。然后我试图从列表中找到逗号并将它们分开。现在我想从列表元素中删除逗号 (,)。

这是我的代码:

text_file = open("Beatles.txt", "r")
lines= text_file.read().split()
x.lower() for x in ["A","B","C"]]
re.findall(r"[\w]+|[.,!?;]", "Hello, I'm a string!")

我的输出是:

['她', '爱', ',', '你', ',', ',', ',', ',', '是的', ',', ',', '是的', ' ,', '她', ',', '爱', ',', '你', ',', ',', '是的', ',', ',', '是的']

我的预期输出是:

['她','爱','你','是的','是的','她','爱','你','是的','是的']

标签: python-3.xstringlist

解决方案


您不需要正则表达式来删除逗号和小写:

s = "She loves you, yeah, yeah, yeah She loves you, yeah, yeah, yeah, yeah You think you lost your love Well, I saw her yesterday It's you she's thinking of And she told me what to say She says she loves you And you know that can't be bad"
s = ''.join(c.lower() for c in s if c != ',')
print(s.split())

输出:

['she', 'loves', 'you', 'yeah', 'yeah', 'yeah', 'she', 'loves', 'you', 'yeah', 'yeah', 'yeah', 'yeah', 'you', 'think', 'you', 'lost', 'your', 'love', 'well', 'i', 'saw', 'her', 'yesterday', "it's", 'you', "she's", 'thinking', 'of', 'and', 'she', 'told', 'me', 'what', 'to', 'say', 'she', 'says', 'she', 'loves', 'you', 'and', 'you', 'know', 'that', "can't", 'be', 'bad']

推荐阅读