【问题标题】:Remove specific punctuation from the list elements in Python从 Python 中的列表元素中删除特定标点符号
【发布时间】:2019-10-09 19:09:49
【问题描述】:

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

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

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

这是我的代码:

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!")

我的输出是:

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

我的预期输出是:

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

【问题讨论】:

  • 你是如何得到你想要的输出的。为什么里面没有thinking这样的词?
  • 这里表示的代码是示例代码。

标签: python-3.x string list


【解决方案1】:

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

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']

【讨论】:

  • 我确实需要一些特定的输出,例如“it's”、“can't”等。我只想删除逗号 (,)。
  • 非常感谢 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-21
  • 2015-09-07
  • 2022-11-14
  • 2013-10-25
相关资源
最近更新 更多