Python: find all possible word combinations with a sequence of characters (word segmentation)

后端 未结 4 2043
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 05:39

I\'m doing some word segmentation experiments like the followings.

lst is a sequence of characters, and output is all the possible words.

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-14 06:16

    #!/usr/bin/env python
    from itertools import combinations
    a = ['a', 'b', 'c', 'd']
    a = "".join(a)
    cuts = []
    for i in range(0,len(a)):
        cuts.extend(combinations(range(1,len(a)),i))
    for i in cuts:
        last = 0
        output = []
        for j in i:
            output.append(a[last:j])
            last = j
        output.append(a[last:])
        print(output)
    

    output:

    zsh 2419 % ./words.py  
    ['abcd']
    ['a', 'bcd']
    ['ab', 'cd']
    ['abc', 'd']
    ['a', 'b', 'cd']
    ['a', 'bc', 'd']
    ['ab', 'c', 'd']
    ['a', 'b', 'c', 'd']
    

提交回复
热议问题