将没有换行符的字符串拆分为最大列数的行列表
我有一段很长的字符串(包含多个段落),我需要把它分成一系列的行字符串。判断什么算作一行的标准是:
- 这一行的字符数小于或等于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 个回答
4
你可能想用标准库里的 textwrap 函数:
14
编辑
你要找的是 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