我有一些問題試圖通過標點符號來分割字符串。具體來說,屬於string.punctuation的每個字符。例如,對於串基於標點符號化字符串
輸入:
"Hi. How2 are you doing?? "
我想的輸出:
['Hi', '.', 'How2', 'are', 'you', 'doing', '?', '?')
供參考string.punctuation是:
'!"#$%&\'()*+,-./:;<=>[email protected][\\]^_`{|}~'
我想任何字符在字符串中成爲自己的令牌。
我目前試過使用re.split()
。然而,我所能達到的只是基於非單詞字符的分裂。例如:
print([i for i in re.split(r'(\W+)', 'hi. how are you doing') if i])
其給出的輸出:
['hi', '. ', 'how', ' ', 'are', ' ', 'you', ' ', 'doing', '??']
此外,兩個'??'
應當被拆分。有什麼建議麼?
只是一個小的評論,你不需要說[我爲我在re.split(...)如果我] ...「如果我「完全是多餘的,並且如果你真的不能只說print(re.split(...))<我不知道,我不熟悉Python 3的print()或者re模塊的split() )>你可以說print(list(re.split())) – 2014-11-22 19:14:49