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

Kar*_*rim 6 python text-manipulation

我有一个长字符串(多个段落),我需要将其拆分为一个行字符串列表.确定"线"的基础是:

  • 行中的字符数小于或等于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."
Run Code Online (Sandbox Code Playgroud)

输出:

"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."
Run Code Online (Sandbox Code Playgroud)

Nad*_*mli 13

编辑

您正在寻找的是textwrap,但这只是解决方案的一部分,而不是完整的解决方案.要考虑换行,您需要这样做:

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
Run Code Online (Sandbox Code Playgroud)