gpt4 book ai didi

python - 适当的长文本自动换行

转载 作者:太空宇宙 更新时间:2023-11-03 13:46:27 30 4
gpt4 key购买 nike

我有一个 1000 个字符长的文本字符串,我想将此文本拆分为小于 100 个字符的 block 而不拆分整个单词(99 个字符可以,但 100 个字符不行)。包装/拆分只能在空格上进行:

例子:

text = "... this is a test , and so on..."
^
#position: 100

应该拆分为:

newlist = ['... this is a test ,', ' and so on...', ...]

我想获得一个列表newlist,其中的文本被正确地分割成可读的(不是裁剪过的) block 。你会怎么做?

最佳答案

使用 textwrap模块的 wrap功能。下面的示例将行拆分为 10 个字符宽:

In [1]: import textwrap

In [2]: textwrap.wrap("... this is a test , and so on...", 10)
Out[2]: ['... this', 'is a test', ', and so', 'on...']

关于python - 适当的长文本自动换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19457637/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com