![](/img/trans.png)
[英]Split string based on certain words and remove certain special characters in Python
[英]How do You Split String into Words and Special Characters in Python?
我想将字符串拆分为单词[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中实现?
怎么样:
re.findall(r"[A-Za-z@#]+|\S", message)
该模式匹配单词字符的任何序列(此处定义为字母加@
和#
),或任何单个非空白字符。
您可以使用字符类来指定不需要分割的所有字符。 [^\\w@#]
-表示除字母/数字/下划线/ @ /#之外的所有字符
然后,您也可以使用re.split
括号捕获特殊字符。
filter(None, re.split(r'\s|([^\w@#])', message))
进行filter
是为了除去空字符串,避免在特殊字符之间进行拆分。 \\s|
部分是为了不捕获空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.