6

行文字列のリストに分割する必要がある長い文字列(複数の段落)があります。「線」を作るものの決定は以下に基づいています:

  • 行の文字数がX以下(Xは1行あたりの固定列数_)
  • または、元の文字列に改行があります(これにより、新しい「行」が強制的に作成されます。

私はこれをアルゴリズムで実行できることを知っていますが、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."
4

2 に答える 2

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
于 2009-09-10T17:05:17.237 に答える
4

おそらく、標準ライブラリの textwrap 関数を使用したいと思うでしょう:

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

于 2009-09-10T17:03:29.760 に答える