将第N个字符分割成字符串,并使用不同的分隔符将其重新连接在一起

问题描述 投票:4回答:3

我尝试在带有不同分隔符的句子中使用文本换行。这正是我想要得到的输出:

'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()功能结合起来可以做一个我想做的更好的方法,但是我找不到如何做。请,您对如何实现这一目标有任何想法吗?

python string delimiter word-wrap
3个回答
5
投票

这里是一个您可以尝试的班轮:

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

2
投票

自动换行为您提供了可重复的文本。如果可以使用分隔符创建一个可迭代的对象,则可以使用"".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.

© www.soinside.com 2019 - 2024. All rights reserved.