un approccio non-regex diverso dagli altri:
>>> 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']
potrebbe usare dict.fromkeys
e .get
al posto del lambda
, immagino.
[modifica]
Qualche spiegazione:
groupby
accetta due argomenti, un iterabile ed un keyfunction (opzionale). Esso scorre iterable le raggruppa con il valore del 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'])]
dove termini con valori contigui del keyfunction sono raggruppati insieme. (Questa è una fonte comune di bug, in realtà - le persone dimenticano che devono prima ordinare il keyfunc se vogliono raggruppare termini che potrebbero non essere sequenziali.)
Come ho intuito @JonClements, cosa avevo in mente era
>>> 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']
per il caso in cui stavamo combinando i separatori. .get
restituisce None
se il valore non è nel dict.
Sto indovinando dal momento che avete accettato la risposta di DSM si intende per i caratteri di punteggiatura consecutivi per rimanere raggruppati insieme? – John
@johnthexiii, l'ho accettato perché non usava 're'. L'opzione per raggruppare i separatori consecutivi è un ulteriore vantaggio, anche se sono sicuro che può essere fatto facilmente anche con regex. – blz