python - 如何在单词和标点符号上拆分字符串
问题描述
我对 Python 比较陌生,有没有办法可以将字符串"James kicked Bob's ball, laughed and ran away."
拆分为以下内容,所以我在 list items 中有单词和标点符号["James", "kicked", "Bob's", "ball", ",", "laughed", "and", "ran", "away", "."]
。有没有办法在 python 中做到这一点?
解决方案
你可以试试这个:
import re
str = "James kicked Bob's ball, laughed and ran away."
x = re.findall(r"[\w']+|[.,!?;]", str)
print(x)
输出:
['James', 'kicked', "Bob's", 'ball', ',', 'laughed', 'and', 'ran', 'away', '.']
推荐阅读
- python - 将两个 csv 文件与一个共同元素组合并在没有熊猫的情况下进行排序
- sql-server - 没有提供 mssql-server-is 所需的 python
- robotframework - 使用 Robot 与远程主机并行 SSH 连接
- azure - 使用应用服务节省 Azure 计费成本?
- html - 需要添加文本和链接到 Header
- django - How can i customize the label of model form?
- kotlin - Is it bad practice to chain Kotlin null safety operator when dealing with immutable variables and properties?
- python - 在 Python 中使用时间戳比较文件
- flutter - Use popUntil Navigator method with custom transition animation
- unix - Why the keyboard input is written back to IO bus in xv6?