不同的非正則表達式的方式從別人:
>>> import string
>>> from itertools import groupby
>>>
>>> special = set(string.punctuation + string.whitespace)
>>> s = "One two three tab\ttabandspace\t end"
>>>
>>> split_combined = [''.join(g) for k, g in groupby(s, lambda c: c in special)]
>>> split_combined
['One', ' ', 'two', ' ', 'three', ' ', 'tab', '\t', 'tabandspace', '\t ', 'end']
>>> split_separated = [''.join(g) for k, g in groupby(s, lambda c: c if c in special else False)]
>>> split_separated
['One', ' ', 'two', ' ', 'three', ' ', 'tab', '\t', 'tabandspace', '\t', ' ', 'end']
能使用的lambda
代替dict.fromkeys
和.get
,我猜。
[編輯]
一些說明:
groupby
接受兩個參數,可迭代和(可選的)keyfunction。它通過循環可迭代和組將它們與keyfunction的值:
>>> groupby("sentence", lambda c: c in 'nt')
<itertools.groupby object at 0x9805af4>
>>> [(k, list(g)) for k,g in groupby("sentence", lambda c: c in 'nt')]
[(False, ['s', 'e']), (True, ['n', 't']), (False, ['e']), (True, ['n']), (False, ['c', 'e'])]
其中具有keyfunction的連續值方面組合在一起。 (這實際上是一個常見的錯誤來源 - 人們忘記了如果他們想要將可能不連續的術語分組,那麼他們必須首先按keyfunc進行排序。)
正如@JonClements猜想的那樣,我想到的是
>>> special = dict.fromkeys(string.punctuation + string.whitespace, True)
>>> s = "One two three tab\ttabandspace\t end"
>>> [''.join(g) for k,g in groupby(s, special.get)]
['One', ' ', 'two', ' ', 'three', ' ', 'tab', '\t', 'tabandspace', '\t ', 'end']
對於我們合併分隔符的情況。如果該值不在字典中,則.get
返回None
。
我猜,因爲你接受你打算連續標點符號DSM的回答保持組合在一起? – John
@johnthexiii,我接受它,因爲它沒有使用're'。將連續分隔符分組的選項是一個額外的好處,但我相信它也可以使用正則表達式輕鬆完成。 – blz