我尝试用不同的分隔符在句子中使用文本换行。这正是我希望得到的输出:
'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()
函数可以更好地完成我想做的事情,但我找不到方法。请问,你对如何做到这一点有什么想法吗
这里有一条你可以试试的单行线:
Wrap为您提供文本的可编辑部分。如果可以使用分隔符创建iterable,则可以使用
"".join(t for pair in zip(wrapped_chunks, separators) for t in pair)
将其连接起来您可以使用无限生成器创建分隔符:
这将给您一个过多的分隔符,因此您可能希望删除它或特别附加
wrapped_chunks
的最后一项如果您想在几个不同的分隔符之间切换,您可以使用
itertools.cycle(["SEP1", "SEP2", "SEP3"])
来生成重复的令牌循环试试这个:
相关问题 更多 >
编程相关推荐