python-3.x - 从 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!")
我的输出是:
['她', '爱', ',', '你', ',', ',', ',', ',', '是的', ',', ',', '是的', ' ,', '她', ',', '爱', ',', '你', ',', ',', '是的', ',', ',', '是的']
我的预期输出是:
['她','爱','你','是的','是的','她','爱','你','是的','是的']
解决方案
您不需要正则表达式来删除逗号和小写:
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']
推荐阅读
- javascript - 如何等待变量以角度设置
- post - Angular 7 HttpClient POST - 错误请求
- php - laravel 第二个连接返回查询为空
- r - GGplot 未在 RStudio 上显示
- laravel - Laravel Nova:替换主路由并作为默认应用程序运行
- python - 计算检测到的对象像素数占图片总像素数的百分比
- swift - 使用 Any 而不是泛型
- docker - 如何配置 docker-compose 卷访问权限
- database - MongoDB WiredTiger 是否使用聚集索引?
- android - Kotlin,警报管理器不触发