2

Pythonは初めてですが、私のプログラムについて助けが必要です。書式設定されていないテキストドキュメントを取り込み、書式設定(ページ幅と余白の設定)を行い、新しいテキストドキュメントを出力するコードがあります。最終的な出力を生成するこの関数を除いて、私のコード全体は正常に機能します。

問題コードのセグメントは次のとおりです。

def process(document, pagewidth, margins, formats):
    res = []
    onlypw = []
    pwmarg = []
    count = 0
    marg = 0


    for segment in margins: 

        for i in range(count, segment[0]):
            res.append(document[i])
        text = ''

    foundmargin = -1
    for i in range(segment[0], segment[1]+1):
        marg = segment[2]
        text = text + '\n' + document[i].strip(' ')

    words = text.split()

注:セグメント[0]はドキュメントの先頭を意味し、セグメント[1]は、範囲について疑問がある場合はドキュメントの末尾を意味します。私の問題は、テキストを単語にコピーすると(words = text.split())、空白行が保持されないことです。私が取得する必要がある出力は次のとおりです。

      This is my substitute for pistol and ball. With a
      philosophical flourish Cato throws himself upon his sword; I
      quietly take to the ship. There is nothing surprising in
      this. If they but knew it, almost all men in their degree,
      some time or other, cherish very nearly the same feelings
      towards the ocean with me.

      There now is your insular city of the Manhattoes, belted
      round by wharves as Indian isles by coral reefs--commerce
      surrounds it with her surf.

そして、私の現在の出力は次のようになります。

      This is my substitute for pistol and ball. With a
      philosophical flourish Cato throws himself upon his sword; I
      quietly take to the ship. There is nothing surprising in
      this. If they but knew it, almost all men in their degree,
      some time or other, cherish very nearly the same feelings
      towards the ocean with me. There now is your insular city of
      the Manhattoes, belted round by wharves as Indian isles by
      coral reefs--commerce surrounds it with her surf. 

空白行が保持されないため、テキストを単語にコピーすると問題が発生することはわかっています。空白行と単語を確実にコピーするにはどうすればよいですか?コードを追加するか、詳細を追加する必要があるかをお知らせください。

4

2 に答える 2

4

最初に少なくとも2つの改行で分割し、次に単語で分割します。

import re

paragraphs = re.split('\n\n+', text)
words = [paragraph.split() for paragraph in paragraphs]

これで、段落ごとに1つずつリストのリストができました。段落ごとにこれらを処理します。その後、2つの改行を挿入して、全体を新しいテキストに再結合できます。

私は以前re.split()、2つ以上の改行で区切られた段落をサポートしていました。text.split('\n\n')段落間に改行が2つしかない場合は、単純なものを使用できます。

于 2013-03-14T20:26:34.833 に答える
1

正規表現を使用して、分割するのではなく、単語と空白行を見つけます

m = re.compile('(\S+|\n\n)')
words=m.findall(text)
于 2013-03-14T20:34:07.743 に答える