3

で始まるデータでいっぱいのテキスト ファイルがあります。

#Name
#main

その後にたくさんの数字が続き、ファイルは次で終わります

#extra
!side

ここに小さなスニペットがあります

#Name
#main
60258960
33031674
72302403
#extra
!side

数字だけ読みたい。しかし、ここにキックがあります。私は、それらをそれぞれ独自のストリングにしたいと考えています。

だから私はヘッダーの後に始まる読み方を知っています

read=f.readlines()[3:]

しかし、私は他のすべてに困惑しています。助言がありますか?

4

5 に答える 5

1

.readlines()入力ファイルがメモリに問題なく収まることがわかっている場合にのみ使用してください。一度にすべての行を読み取ります。

ほとんどの場合、一度に 1 つの入力行を読み取ることができます。そのためには、ファイル ハンドル オブジェクトを反復処理するだけです。

特別でトリッキーな入力処理が必要な場合は、次のようなジェネレーター関数で処理をカプセル化することをお勧めします。

def do_something_with_point(point):
    print(point)

class BadInputFile(ValueError):
    pass

def read_points_data(f):
    try:
        line = next(f)
        if not line.startswith("#Name"):
            raise BadInputFile("file does not start with #Name")

        line = next(f)
        if not line.startswith("#main"):
            raise BadInputFile("second line does not start with #main")
    except StopIteration:
        raise BadInputFile("truncated input file")

    # use enumerate() to count input lines; start at line number 3
    # since we just handled two lines of header
    for line_num, line in enumerate(f, 3):
        if line.startswith("#extra"):
            break
        else:
            try:
                yield int(line)
            except ValueError:
                raise BadInputFile("illegal line %d: %s" % (line_num, line))
            # if you really do want strings: yield line
    else:
        # this code will run if we never see a "#extra" line
        # if break is executed, this doesn't run.
        raise BadInputFile("#extra not seen")

    try:
        line = next(f)
        if not line.startswith("!side"):
            raise BadInputFile("!side not seen after #extra")
    except StopIteration:
        raise BadInputFile("input file truncated after #extra")

with open("points_input_file.txt") as f:
    for point in read_points_data(f):
        do_something_with_point(point)

この入力関数は入力を完全に検証し、入力に誤りがある場合は例外を発生させることに注意してください。しかし、入力データを使用するループは単純でクリーンです。使用するコードをread_points_data()整理できます。

入力ポイントを値にread_points_data()変換しました。intポイントを文字列として本当に必要な場合は、コードを変更できます。私はあなたに思い出させるためにそこにコメントを残しました。

于 2013-04-29T23:50:30.920 に答える
1

私はこのようなことをします:

nums = []
for line in f:
  stripped = line.rstrip('\n')
  if stripped.isnumeric():
    nums.append(stripped)

nums数字のある行のみが含まれます。数値が適切な形式である場合、つまり、負でも 16 進数でもないことを意味します。正確に一致させるには正規表現が必要です。

于 2013-04-11T23:35:30.820 に答える