Python-text-processing-python-reformatting-paragraphs

提供:Dev Guides
移動先:案内検索

Python-段落の再フォーマット

大量のテキストを処理して見やすい形式にする場合、段落の書式設定が必要です。 特定の幅で各行を印刷するか、詩を印刷するときに次の各行のインデントを増やしたい場合があります。 この章では、 textwrap3 という名前のモジュールを使用して、必要に応じて段落をフォーマットします。

まず、次のように必要なパッケージをインストールする必要があります

 pip install textwrap3

固定幅への折り返し

この例では、段落の各行に30文字の幅を指定します。 widthパラメーターの値を指定して、wrap関数を使用します。

from textwrap3 import wrap

text = 'In late summer 1945, guests are gathered for the wedding reception of Don Vito Corleones daughter Connie (Talia Shire) and Carlo Rizzi (Gianni Russo). Vito (Marlon Brando), the head of the Corleone Mafia family, is known to friends and associates as Godfather. He and Tom Hagen (Robert Duvall), the Corleone family lawyer, are hearing requests for favors because, according to Italian tradition, no Sicilian can refuse a request on his daughters wedding day.'

x = wrap(text, 30)
for i in range(len(x)):
    print(x[i])

上記のプログラムを実行すると、次の出力が得られます-

In late summer 1945, guests
are gathered for the wedding
reception of Don Vito
Corleones daughter Connie
(Talia Shire) and Carlo Rizzi
(Gianni Russo). Vito (Marlon
Brando), the head of the
Corleone Mafia family, is
known to friends and
associates as Godfather. He
and Tom Hagen (Robert Duvall),
the Corleone family lawyer,
are hearing requests for
favors because, according to
Italian tradition, no Sicilian
can refuse a request on his
daughters wedding day.

可変インデント

この例では、印刷される詩の各行のインデントを増やします。

import textwrap3

FileName = ("path\poem.txt")

print("**Before Formatting**")
print(" ")

data=file(FileName).readlines()
for i in range(len(data)):
   print data[i]

print(" ")
print("**After Formatting**")
print(" ")
data=file(FileName).readlines()
for i in range(len(data)):
   dedented_text = textwrap3.dedent(data[i]).strip()
   print dedented_text

上記のプログラムを実行すると、次の出力が得られます-

**Before Formatting**

 Summer is here.
  Sky is bright.
    Birds are gone.
     Nests are empty.
      Where is Rain?

**After Formatting**

Summer is here.
Sky is bright.
Birds are gone.
Nests are empty.
Where is Rain?