繁体   English   中英

Python - 按顺序拆分字符串

[英]Python - get all in order splits of a string

也就是说,对于一个句子,将它分解为所有可能的有序单词组合,没有遗漏任何单词

例如,对于输入“The cat sat on the mat”

输出

[("The", "cat sat on the mat"),
("The cat", "sat on the mat"),  
("The cat", "sat", "on the mat")] #etc

但不是

("The mat", "cat sat on the") # out of order
("The cat"), ("mat") # words missing

我查看了 itertools 中的方法,但看不到它们的作用,因为组合会遗漏项目(“猫”、“垫子”)并且排列会改变顺序。

我是否遗漏了这些工具中的某些东西,或者它们只是不正确的东西?

(为了清楚起见,这不是关于如何拆分字符串的问题,而是关于如何获得组合的问题)

根据 WordAligned 的这篇博客文章的启发,修改Raymond Hettinger 的Python 3分区配方,以及您列表中的每个分区案例,我们可以使用 itertools 中的chaincombinations来完成此操作。

from itertools import chain, combinations
def partition(iterable):
    n = len(input_list)
    b, mid, e = [0], list(range(1, n)), [n]
    getslice = input_list.__getitem__
    splits = (d for i in range(n) for d in combinations(mid, i))
    return [[input_list[sl] for sl in map(slice, chain(b, d), chain(d, e))]
            for d in splits]

演示

>>> print(partition(input_list))
[[['The', 'cat', 'sat', 'on', 'the', 'mat']], [['The'], ['cat', 'sat', 'on', 'the', 'mat']], [['The', 'cat'], ['sat', 'on', 'the', 'mat']], [['The', 'cat', 'sat'], ['on', 'the', 'mat']], [['The', 'cat', 'sat', 'on'], ['the', 'mat']], [['The', 'cat', 'sat', 'on', 'the'], ['mat']], [['The'], ['cat'], ['sat', 'on', 'the', 'mat']], [['The'], ['cat', 'sat'], ['on', 'the', 'mat']], [['The'], ['cat', 'sat', 'on'], ['the', 'mat']], [['The'], ['cat', 'sat', 'on', 'the'], ['mat']], [['The', 'cat'], ['sat'], ['on', 'the', 'mat']], [['The', 'cat'], ['sat', 'on'], ['the', 'mat']], [['The', 'cat'], ['sat', 'on', 'the'], ['mat']], [['The', 'cat', 'sat'], ['on'], ['the', 'mat']], [['The', 'cat', 'sat'], ['on', 'the'], ['mat']], [['The', 'cat', 'sat', 'on'], ['the'], ['mat']], [['The'], ['cat'], ['sat'], ['on', 'the', 'mat']], [['The'], ['cat'], ['sat', 'on'], ['the', 'mat']], [['The'], ['cat'], ['sat', 'on', 'the'], ['mat']], [['The'], ['cat', 'sat'], ['on'], ['the', 'mat']], [['The'], ['cat', 'sat'], ['on', 'the'], ['mat']], [['The'], ['cat', 'sat', 'on'], ['the'], ['mat']], [['The', 'cat'], ['sat'], ['on'], ['the', 'mat']], [['The', 'cat'], ['sat'], ['on', 'the'], ['mat']], [['The', 'cat'], ['sat', 'on'], ['the'], ['mat']], [['The', 'cat', 'sat'], ['on'], ['the'], ['mat']], [['The'], ['cat'], ['sat'], ['on'], ['the', 'mat']], [['The'], ['cat'], ['sat'], ['on', 'the'], ['mat']], [['The'], ['cat'], ['sat', 'on'], ['the'], ['mat']], [['The'], ['cat', 'sat'], ['on'], ['the'], ['mat']], [['The', 'cat'], ['sat'], ['on'], ['the'], ['mat']], [['The'], ['cat'], ['sat'], ['on'], ['the'], ['mat']]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM