我尝试在带有不同分隔符的句子中使用文本换行。请准确找到我想作为输出得到的内容:
'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()
功能结合起来可以做一个我想做的更好的方法,但是我找不到如何做。拜托,您对实现这一目标有任何想法吗?非常感谢您的帮助。
这里是一个您可以尝试的班轮:
text = ''.join([(f'[SEPARATOR{i}]' if i else '') + w
for i, w in enumerate(wrap(sentence, 20))])
自动换行为您提供了可重复的文本。如果可以使用分隔符创建一个可迭代的对象,则可以使用"".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
的最后一项。
尝试一下:
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.
您可以将itertools.chain与zip()结合使用:
import itertools
from textwrap import wrap
sentence = '''here are third-party extensions like Scener that allow us to watch content.'''
separator = ['[SEPARATOR%s]' % str(i) for i in range(0,4)]
print ("".join(list(itertools.chain(*zip(separator, wrap(sentence, 20))))))
输出:
[SEPARATOR0]here are third-party[SEPARATOR1]extensions like[SEPARATOR2]Scener that allow us[SEPARATOR3]to watch content.