Разделите строку на каждый N-й символ и объедините его с разными разделителями - PullRequest
4 голосов
/ 29 мая 2020

Я пытаюсь использовать перенос текста в предложение с разными разделителями. Это именно то, что я хотел бы получить на выходе:

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

Затем я пробовал использовать для l oop внутри разделителя, но тоже безуспешно ...:

[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 голосов
/ 29 мая 2020

Вот один лайнер, который вы можете попробовать:

text = ''.join([(f'[SEPARATOR{i}]' if i else '') + w
                for i, w in enumerate(wrap(sentence, 20))])
2 голосов
/ 29 мая 2020

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 голос
/ 29 мая 2020

Попробуйте следующее:

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.

...