python - Split a string into all possible ordered phrases -
i trying explore functionality of python's built-in functions. i'm trying work takes string such as:
'the fast dog'
and break string down possible ordered phrases, lists. example above output following:
[['the', 'fast dog'], ['the fast', 'dog'], ['the', 'fast', 'dog']]
the key thing original ordering of words in string needs preserved when generating possible phrases.
i've been able function work can this, cumbersome , ugly. however, wondering if of built-in functionality in python might of use. thinking might possible split string @ various white spaces, , apply recursively each split. might have suggestions?
using itertools.combinations:
import itertools def break_down(text): words = text.split() ns = range(1, len(words)) # n = 1..(n-1) n in ns: # split 2, 3, 4, ..., n parts. idxs in itertools.combinations(ns, n): yield [' '.join(words[i:j]) i, j in zip((0,) + idxs, idxs + (none,))]
example:
>>> x in break_down('the fast dog'): ... print(x) ... ['the', 'fast dog'] ['the fast', 'dog'] ['the', 'fast', 'dog'] >>> x in break_down('the fast dog'): ... print(x) ... ['the', 'really fast dog'] ['the really', 'fast dog'] ['the fast', 'dog'] ['the', 'really', 'fast dog'] ['the', 'really fast', 'dog'] ['the really', 'fast', 'dog'] ['the', 'really', 'fast', 'dog']
Comments
Post a Comment