每隔N个字符拆分字符串,并用不同的分隔符重新组合

4
我尝试在带有不同分隔符的句子中使用文本换行。这正是我想要得到的输出结果:
'here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.'

这是我第一次尝试使用.join()wrap(),但失败了:

[In] : 
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

separator = '[SEPARATOR]'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR]extensions like[SEPARATOR]Scener that allow us[SEPARATOR]to watch content.'

然后,我尝试在分隔符内部使用for循环,但也没有成功...:

[In] : 
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

for i in range(1, 4):
    separator = '[SEPARATOR' + str(i) + ']'

text = separator.join(wrap(sentence, 20))

[Out] :
'here are third-party[SEPARATOR3]extensions like[SEPARATOR3]Scener that allow us[SEPARATOR3]to watch content.'

也许将.split().join()函数组合起来使用可以更好地实现我想要的效果,但我不知道如何做。请问你有关于如何实现这一点的任何想法吗?

3个回答

5

这是一个可以尝试的一行代码:

text = ''.join([(f'[SEPARATOR{i}]' if i else '') + w
                for i, w in enumerate(wrap(sentence, 20))])

我必须感谢这里的每个人。这个答案解决了我的问题,但是对于那些没有数字分隔符的人来说,如果分隔符是A、B、C而不是数字,我们该怎么办呢?我想我们不能使用enumerate,对吧?再次感谢。 - prog-amateur
请查看 @Gabip 的回答来回答我关于字符串分隔符的问题。 - prog-amateur

2

Wrap会给你一个文本的可迭代对象。如果你可以使用分隔符创建一个可迭代对象,你可以使用"".join(t for pair in zip(wrapped_chunks, separators) for t in pair)将它们连接起来。

你可以用一个无限生成器来创建你的分隔符:

def inf_separators():
    index = 1
    while True:
        yield f"SEPARATOR{index}"
        index = index + 1

这将会使你多出一个分隔符,因此你可能需要删除它或者特别地添加wrapped_chunks的最后一项。
如果你想在几个不同的分隔符之间交替使用,可以使用itertools.cycle(["SEP1", "SEP2", "SEP3"])生成重复循环的标记。

1

试试这个:

from textwrap import wrap

sentence = '''here are third-party extensions like Scener that allow us to watch content.'''

new_sentence = ""
parts = wrap(sentence, 20)
for i, part in enumerate(parts):
    new_sentence += part
    # adding separator after each part except for the last one
    if i < len(parts) - 1:
        new_sentence += f"[SEPARATOR{i+1}]"
print(new_sentence)

# output: here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.


1
我也应该接受你的答案,因为它不仅解决了我的问题,还解决了那些将分隔符作为字符串(如SEPARATOR_A、SEPARATOR_B等)的人的问题。非常感谢。 - prog-amateur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接