Skip to main content
 首页 » 编程设计

Python-按顺序拆分字符串

2025年04月02日43zhenyulu

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

例如,对于输入 “猫坐在垫子上”

输出

[("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 中的方法,但看不到它们的作用,因为组合会遗漏项目(“猫”、“垫子”)并且排列会改变顺序。

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

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

请您参考如下方法:

修改 Raymond Hettinger's partition recipe适用于受 this blog post 启发的 Python 3来自 WordAligned,以及您列表中的每个分区案例,我们可以使用 itertools 中的 chain 和 combinations 来完成此操作。

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']]]