不同的非正则表达式的方式从别人:
>>> 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