代码之家  ›  专栏  ›  技术社区  ›  Karim

将没有换行符的字符串拆分为具有最大列数的行列表

  •  6
  • Karim  · 技术社区  · 16 年前

    我有一个长字符串(多个段落),需要将其拆分为一个字符串列表。“线条”的确定基于:

    • 行中的字符数小于或等于x(其中x是每行固定的列数)
    • 或者,原始字符串中有新行(这将强制创建新的“行”)。

    我知道我可以从算法上实现这一点,但我想知道Python是否有可以处理这种情况的功能。它本质上是一个包裹字符串的单词。

    而且,顺便说一下,输出行必须在单词边界上断开,而不是字符边界。

    以下是输入和输出示例:

    输入:

    "Within eight hours of Wilson's outburst, his Democratic opponent, former-Marine Rob Miller, had received nearly 3,000 individual contributions raising approximately $100,000, the Democratic Congressional Campaign Committee said.
    
    Wilson, a conservative Republican who promotes a strong national defense and reining in the size of government, won a special election to the House in 2001, succeeding the late Rep. Floyd Spence, R-S.C. Wilson had worked on Spence's staff on Capitol Hill and also had served as an intern for Sen. Strom Thurmond, R-S.C."
    

    输出:

    "Within eight hours of Wilson's outburst, his"
    "Democratic opponent, former-Marine Rob Miller,"
    " had received nearly 3,000 individual "
    "contributions raising approximately $100,000,"
    " the Democratic Congressional Campaign Committee"
    " said."
    ""
    "Wilson, a conservative Republican who promotes a "
    "strong national defense and reining in the size "
    "of government, won a special election to the House"
    " in 2001, succeeding the late Rep. Floyd Spence, "
    "R-S.C. Wilson had worked on Spence's staff on "
    "Capitol Hill and also had served as an intern"
    " for Sen. Strom Thurmond, R-S.C."
    
    2 回复  |  直到 16 年前
        1
  •  13
  •   Nadia Alramli    16 年前

    编辑

    你要找的是 textwrap 但这只是解决方案的一部分,而不是完整的解决方案。要将newline考虑在内,您需要执行以下操作:

    from textwrap import wrap
    '\n'.join(['\n'.join(wrap(block, width=50)) for block in text.splitlines()])
    
    >>> print '\n'.join(['\n'.join(wrap(block, width=50)) for block in text.splitlines()])
    
    Within eight hours of Wilson's outburst, his
    Democratic opponent, former-Marine Rob Miller, had
    received nearly 3,000 individual contributions
    raising approximately $100,000, the Democratic
    Congressional Campaign Committee said.
    
    Wilson, a conservative Republican who promotes a
    strong national defense and reining in the size of
    government, won a special election to the House in
    2001, succeeding the late Rep. Floyd Spence,
    R-S.C. Wilson had worked on Spence's staff on
    Capitol Hill and also had served as an intern for
    Sen. Strom Thurmond
    
        2
  •  4
  •   Paul McMillan    16 年前

    您可能希望使用标准库中的textfarp函数:

    http://docs.python.org/library/textwrap.html