5

DictReader()を使用して辞書に入力しようとしている一連の.srcファイルがあります。ファイルは次のようになります(ヘッダーと最初の行のみ)。

SRC V2.0.. ........Time Id Event T Conf .Northing ..Easting ...Depth Velocity .NN_Err .EE_Err .DD_Err .NE_Err .ND_Err .ED_Err Ns Nu uSt ....uMag Nt tSt ....tMag .MomMag SeiMoment ...Energy ...Es/Ep .SourceRo AspRadius .StaticSD AppStress DyStressD MaxDispla PeakVelPa PeakAccPa PSt
07-30-2010 07:43:56.543 ND     0 e 0.00    152.54    746.45  1686.31     6000   11.76   11.76   11.76    0.00    0.00    0.00 30  0 num    -9.90 30 utm    -3.21   -1.12 2.06e+007 2.22e+000 20.93    6.08e+000 0.00e+000 3.83e+004 1.49e+003 0.00e+000 1.52e-005 1.50e-003 0.00e+000   1

とにかく、以下は私のコードです:

import csv

Time = {}
Northing = {}
source_file = open(NNSRC, 'rb')
for line in csv.DictReader(source_file, delimiter = '\t'):
    Time = line['........Time'].strip()
    Northing = line['.Northing'].strip()

print Time, Northing

次のエラーが発生します。

Traceback (most recent call last):
  File "C:\Python26\Lib\site-packages\xy\NNFindStages.py", line 101, in <module>
    Time = line['........Time'].strip()
KeyError: '........Time'

ファイル自体を変更せずに、ヘッダーがファイル内でフォーマットされる奇妙な方法をどのように説明できますか?

どんな助けでも大歓迎です!

4

1 に答える 1

8

ヘッダー行はタブを使用していません。

タブなしでデータを再作成すると、csvモジュールによって返される行には1つの(長い)キーしか含まれていません。実際のタブで再作成すると、次のようになります。

>>> source_file = open('out.csv', 'rb')
>>> reader = csv.DictReader(source_file, delimiter = '\t')
>>> line = reader.next()
>>> len(line)
37
>>> line.keys()
['Id', '..Easting', '.NE_Err', 'uSt', 'SeiMoment', 'MaxDispla', 'tSt', 'Ns', 'Nt', 'Nu', '.Northing', '.DD_Err', '...Energy', '....uMag', 'V2.0..', 'DyStressD', 'SRC', 'PeakAccPa', '.SourceRo', '........Time', '.EE_Err', 'T', 'Velocity', 'PeakVelPa', 'AspRadius', '...Depth', 'PSt', '....tMag', '.MomMag', 'AppStress', '...Es/Ep', '.ED_Err', 'Event', '.ND_Err', 'Conf', '.StaticSD', '.NN_Err']
>>> line['........Time']
'ND'
>>> line['.Northing']
'746.45'

値はストリッピングする必要がないことに注意してください。モジュールは、余分な空白を処理します。

ヘッダーを個別に読み取り、それをクリーンアップしてから、残りのデータをcsvモジュールで処理できます。

source_file = open(NNSRC, 'rb')
header = source_file.readline()
source_file.seek(len(header))  # reset read buffer

headers = [h.strip('.') for h in header.split()]
headers = ['Date'] + headers[2:]  # Replace ['SRC', 'V2.0'] with a Date field instead
for line in csv.DictReader(source_file, fieldnames=headers, delimiter = '\t'):
    # process line

上記のコードは、ヘッダー行を個別に読み取り、分割して余分な.ピリオドを削除し、より実用的な列キーを作成してから、readlineバッファーをリセットしてファイルを設定します(呼び出しDictReaderの副作用)。.seek()

于 2012-09-21T16:15:23.110 に答える