2014-10-27 106 views
1

我想將一個字符串分解成字[a-zA-Z]任何特殊字符,它可以包含除@#符號如何將字符串拆分爲單詞和Python中的特殊字符?

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中實現這一點?

+0

那麼,你究竟如何定義「單詞」和「特殊字符」呢? – 2014-10-27 13:12:23

+0

@JoelCornett:我的意思是ASCII特殊字符,http://en.wikipedia.org/wiki/Special_characters – Yax 2014-10-27 13:14:26

+2

不應該用''#單詞',''#word',',''? – fredtantini 2014-10-27 13:19:01

回答

4

如何:

re.findall(r"[[email protected]#]+|\S", message) 

模式的字字符的序列相匹配(在這裏被定義爲字母加@#),或任何單個非空白字符。

+0

這樣做了,但我試過'''.join(message)',我的特殊字符與原來的位置有間隔。 – Yax 2014-10-27 13:24:19

+0

@Yax:恩,是的。你問它的問題是拋棄所有的空間,所以沒有辦法告訴事情之前如何分開。如果你只是在結果中的每個列表項之間插入一個空格,你會得到一堆額外的。 – Blckknght 2014-10-27 13:28:19

+0

難道我沒有辦法解決這個問題嗎?我不會爲此詢問另一個問題。 – Yax 2014-10-27 13:31:30

3

您可以使用一個字符類來指定所有不需要的字符想要進行拆分。 [^\[email protected]#] - 這意味着除字母/數字/下劃線/ @ /以外的每個字符。

然後您可以使用捕獲圓括號re.split來捕獲特殊字符。

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

filter做是爲了從特殊字符之間的分裂刪除空字符串。 \s|部分是這樣的,空間不被捕獲。

+0

這也做到了,但我嘗試了'''.join(message)',我的特殊字符與原來的位置有間隔。 – Yax 2014-10-27 13:24:38

相關問題