首页 > 解决方案 > 如何在单词和标点符号上拆分字符串

问题描述

我对 Python 比较陌生,有没有办法可以将字符串"James kicked Bob's ball, laughed and ran away."拆分为以下内容,所以我在 list items 中有单词和标点符号["James", "kicked", "Bob's", "ball", ",", "laughed", "and", "ran", "away", "."]。有没有办法在 python 中做到这一点?

标签: pythonsplit

解决方案


你可以试试这个:

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

推荐阅读