Skip to main content
 首页 » 编程设计

python之在 Python 中如何将字符串拆分为单词和特殊字符

2025年05月04日23java哥

我想将一个字符串拆分为单词 [a-zA-Z] 以及它可能包含的任何特殊字符,但 @ 和 # 符号

message = "我要被@split,变成#words,以及任何其他不是单词的东西,主要是特殊字符(.,>)"

预期结果:

['我', '是', '到', '是', '@split', ',', '成', '#words', ',', '和', ' any', 'other', 'thing', 'that', 'is', 'not', 'word', ',', 'moSTLy', 'special', 'character', '(', '.' , ',', '>', ')']

如何在 Python 中实现这一点?

请您参考如下方法:

怎么样:

re.findall(r"[A-Za-z@#]+|\S", message) 

该模式匹配任何单词字符序列(此处定义为字母加上 @ 和 #),或任何单个非空白字符。