小编典典

将字符串拆分为最大长度为X的片段-仅在空格处拆分

algorithm

我有一个很长的字符串,我想分成最多X个字符。但是,只能在一个空格处(如果字符串中的某个单词长于X个字符,则将其放入自己的片段中)。

我什至不知道该如何开始… Python

伪代码:

declare a list
while still some string left:
   take the fist X chars of the string
   find the last space in that
   write everything before the space to a new list entry
   delete everything to the left of the space

在编写代码之前,是否有一些python模块可以帮助我(我认为pprint不能做到)?


阅读 263

收藏
2020-07-28

共1个答案

小编典典

使用该textwrap模块(它也会在连字符处断开):

import textwrap
lines = textwrap.wrap(text, width, break_long_words=False)

如果您想自己编写代码,这就是我的处理方式:首先,将文本拆分为单词。从一行中的第一个单词开始,然后迭代其余单词。如果下一个单词适合当前行,则添加它,否则结束当前行并将该单词用作下一行的第一个单词。重复直到所有单词都用完。

这是一些代码:

text = "hello, this is some text to break up, with some reeeeeeeeeaaaaaaally long words."
n = 16

words = iter(text.split())
lines, current = [], next(words)
for word in words:
    if len(current) + 1 + len(word) > n:
        lines.append(current)
        current = word
    else:
        current += " " + word
lines.append(current)
2020-07-28