【问题标题】:Split a string into pieces of max length X - split only at spaces将字符串拆分为最大长度 X 的片段 - 仅在空格处拆分
【发布时间】:2015-11-14 07:38:40
【问题描述】:

我有一个长字符串,我想将它分成最多 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 可以)?

【问题讨论】:

    标签: python algorithm python-3.x text


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-07
      • 2012-05-15
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 2015-10-05
      相关资源
      最近更新 更多