【问题标题】:Python replace spaces in string iteratively [closed]Python迭代地替换字符串中的空格[关闭]
【发布时间】:2014-11-20 13:05:59
【问题描述】:

我试图在 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 个空格。我一直在尝试使用 re.searchre.sub 在 while 循环中,但还没有找到一个好的方法。

【问题讨论】:

  • 那么你自己尝试什么?
  • 你确定要使用正则表达式吗?您希望自己的效率如何?

标签: python regex


【解决方案1】:

使用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

【讨论】:

  • 优秀。干杯!惊人的模块广度!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
  • 2014-10-10
  • 1970-01-01
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多