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

时间:2014-10-27 13:09:52

标签: python regex string

我想将字符串拆分为单词[a-zA-Z]以及除@#符号外可能包含的任何特殊字符

message = "I am to be @split, into #words, And any other thing that is not word, mostly special character(.,>)"

预期结果:

['I', 'am', 'to', 'be', '@split', ',', 'into', '#words', ',', 'And', 'any', 'other', 'thing', 'that', 'is', 'not', 'word', ',', 'mostly', 'special', 'character', '(', '.', ',', '>', ')']

我如何在Python中实现这一目标?

2 个答案:

答案 0 :(得分:5)

怎么样:

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

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

答案 1 :(得分:3)

您可以使用字符类来指定您 想要进行拆分的所有字符。 [^\w@#] - 这意味着除了字母/数字/下划线/ @ /#

之外的每个字符

然后您也可以使用re.split中的捕获括号来捕获特殊字符。

filter(None, re.split(r'\s|([^\w@#])', message))

filter用于删除特殊字符之间拆分的空字符串。 \s|部分是为了不捕获空格。