-1

一部のデータを再フォーマットして、Python で出力ファイルに保存しようとしています。元の行から各行を .strip() し、リストに追加します。元のデータに追加する必要がある値を含む 2 番目のリストを作成し (変更は元のデータを囲みます)、それを繰り返し処理して、文字列書式演算子を使用して変更されたデータを出力ファイルに書き込みます。元データ一覧です。出力では、出力の各レコードに一度だけ提示される情報を挿入する必要があるため、1:1 の出力 (元の行から出力行へ) ではなく、ここで問題が発生すると思います。これが私のコードの例です...

元のデータ:

Client
#ofrecords(as an integer)
Line1ofrecord1
Line2ofrecord1
....
Line1ofrecord2
Line2ofrecord2
....
End

コード:

def shouldbesimple(originalfile):
    inputfile = open(originalfile, "r")
    outputfile = open('finaloutput.txt', "w")
    nowhitespace = originalfile.strip()
    Client = nowhitespace.pop(0)
    Counter = nowhitespace.pop(0)  (each record has exactly the same number of lines)

    #at this point only record information remains in list..

    Header = "stuff at beginning of each record in output"
    Insertclient = "NEEDED {1} CHANGES"
    Line1 = "THINGS I {0} MUST ADD"
    Footer = "stuff at end of each record in output"
    thingstoadd = [Header, Line1, Insertclient, Footer]
    while counter > 0 :
        writetofile = ""
        for element in thingstoadd:
            writetofile = element.format(nowhitespace.pop(0), Client)
            outputfile.write(writetofile + "\n")
        counter = counter - 1
    inputfile.close()
    outputfile.close()

追加するものを反復し始めるまで、すべてが意図したとおりに機能します..

データが意図したとおりに整列されず、「空のリストからポップ」エラーが発生します。writetofile を印刷すると、問題の要素に が表示されたnowhitespace.pop(0)ときだけでなく、繰り返しごとに Python が format ステートメントで操作を実行していることがわかります。{0}

元の情報を文字列データに渡す、または.pop()操作がすべての要素で発生しないようにする、より適切な方法はありますか?

4

1 に答える 1

0

コードをデバッグしようとする代わりに、あなたがやりたいと思うことを私がどのように行うかをお見せしましょう。

import itertools

# from itertools recipes in the docs
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

def shouldbesimple(originalfile):
    with open(originalfile) as inputfile, open('finaloutput.txt', "w") as outputfile:
        client = next(inputfile).rstrip()
        count = int(next(inputfile).rstrip())
        groups = grouper(inputfile, 4)

        Header = "stuff at beginning of each record in output"
        Insertclient = "NEEDED {1} CHANGES"
        Line1 = "THINGS I {0} MUST ADD"
        Footer = "stuff at end of each record in output"
        thingstoadd = [Header, Line1, Insertclient, Footer]

        for _ in range(count):
            for fmt, line in zip(thingstoadd, next(groups)):
                outputfile.write(fmt.format(line.rstrip(), Client) + '\n')

この入力で:

Client
2
Line1ofrecord1
Line2ofrecord1
Line3ofrecord1
Line4ofrecord1
Line1ofrecord2
Line2ofrecord2
Line3ofrecord2
Line4ofrecord2
End

私はこの出力を得る:

THINGS I Line2ofrecord1 MUST ADD
NEEDED Client CHANGES
stuff at end of each record in output
stuff at beginning of each record in output
THINGS I Line2ofrecord2 MUST ADD
NEEDED Client CHANGES
stuff at end of each record in output
于 2013-05-10T22:16:40.060 に答える