
固定幅ファイル解析の最適化
固定幅ファイルを効率的に解析するには、Python の struct モジュールの利用を検討できます。このアプローチでは、次の例に示すように、C を利用して速度を向上させます。
1 2 3 4 5 6 7 8 9 10 11 | <code class = "python" >import struct
fieldwidths = (2, -10, 24)
fmtstring = ' ' .join( '{}{}' .format( abs (fw), 'x' if fw < 0 else 's' ) for fw in fieldwidths)
unpack = struct.Struct(fmtstring).unpack_from # Alias.
parse = lambda line: tuple(s.decode() for s in unpack(line.encode()))
line = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n'
fields = parse(line)
print ( 'fields: {}' .format(fields))</code>
|
ログイン後にコピー
代わりに、文字列スライスを使用することもできます。効率を高めるには、以下の最適化バージョンに示すように、実行時にスライスをコンパイルするラムダ関数を定義することを検討してください。
1 2 3 4 5 6 7 8 9 10 11 | <code class = "python" >def make_parser(fieldwidths):
cuts = tuple(cut for cut in accumulate( abs (fw) for fw in fieldwidths))
pads = tuple(fw < 0 for fw in fieldwidths) # bool flags for padding fields
flds = tuple(zip_longest(pads, (0,) + cuts, cuts))[:-1] # ignore final one
slcs = ', ' .join( 'line[{}:{}]' .format(i, j) for pad, i, j in flds if not pad)
parse = eval ( 'lambda line: ({})\n' .format(slcs)) # Create and compile source code.
# Optional informational function attributes.
parse.size = sum( abs (fw) for fw in fieldwidths)
parse.fmtstring = ' ' .join( '{}{}' .format( abs (fw), 'x' if fw < 0 else 's' )
for fw in fieldwidths)
return parse</code>
|
ログイン後にコピー
以上がPython で固定幅ファイルの解析を最適化する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。