Python迭代地替换字符串中的空格

时间:2014-11-20 13:05:59

标签: python regex

我正试图在python的每个可能位置一次用一个连字符替换空格。例如,the man said hi应生成所有可能的连字符位置的列表,包括多个连字符:

the-man said hi
the man-said hi
the man said-hi 
the-man said-hi
the-man-said hi
the man-said-hi
the-man-said-hi

字符串的长度因空格数而异,因此不能仅修复3个空格。我在while循环中一直在试验re.searchre.sub,但还没有找到一个好方法。

1 个答案:

答案 0 :(得分:0)

使用itertools.product()生成所有空格和短划线组合,然后将字符串重新组合:

from itertools import product

def dashed_combos(inputstring):
    words = inputstring.split()
    for combo in product(' -', repeat=len(words) - 1):
        yield ''.join(w for pair in zip(words, combo + ('',)) for w in pair)

最后一行将这些单词与短划线和空格一起拉开(在末尾添加一个空字符串以组成对),然后展平它并将它们连接成一个单独的字符串。

演示:

>>> for combo in dashed_combos('the man said hi'):
...     print combo
... 
the man said hi
the man said-hi
the man-said hi
the man-said-hi
the-man said hi
the-man said-hi
the-man-said hi
the-man-said-hi

您始终可以使用itertools.islice()跳过该循环的第一次迭代(仅包含空格):

from itertools import product, islice

def dashed_combos(inputstring):
    words = inputstring.split()
    for combo in islice(product(' -', repeat=len(words) - 1), 1, None):
        yield ''.join(w for pair in zip(words, combo + ('',)) for w in pair)

这一切都非常有效;如果您不尝试将所有可能的组合同时存储在内存中,则可以轻松处理数百个单词的输入。

稍微长一点的演示:

>>> for combo in islice(dashed_combos('the quick brown fox jumped over the lazy dog'), 10):
...     print combo
... 
the quick brown fox jumped over the lazy-dog
the quick brown fox jumped over the-lazy dog
the quick brown fox jumped over the-lazy-dog
the quick brown fox jumped over-the lazy dog
the quick brown fox jumped over-the lazy-dog
the quick brown fox jumped over-the-lazy dog
the quick brown fox jumped over-the-lazy-dog
the quick brown fox jumped-over the lazy dog
the quick brown fox jumped-over the lazy-dog
the quick brown fox jumped-over the-lazy dog
>>> for combo in islice(dashed_combos('the quick brown fox jumped over the lazy dog'), 200, 210):
...     print combo
... 
the-quick-brown fox jumped-over the lazy-dog
the-quick-brown fox jumped-over the-lazy dog
the-quick-brown fox jumped-over the-lazy-dog
the-quick-brown fox jumped-over-the lazy dog
the-quick-brown fox jumped-over-the lazy-dog
the-quick-brown fox jumped-over-the-lazy dog
the-quick-brown fox jumped-over-the-lazy-dog
the-quick-brown fox-jumped over the lazy dog
the-quick-brown fox-jumped over the lazy-dog
the-quick-brown fox-jumped over the-lazy dog