解析固定宽度文件(每列在一行中占据特定数量的字符)可能是一项需要效率的任务。以下是关于如何有效实现这一目标的讨论:
考虑一个固定宽度的文件,其中前 20 个字符代表一列,后面的 21-30 代表第二列,依此类推在。给定一行 100 个字符,我们如何有效地将其解析为各自的列?
1.结构模块:
利用 Python 标准库的 struct 模块由于其 C 实现而提供了简单性和速度。下面的代码演示了其用法:
<code class="python">import struct fieldwidths = (2, -10, 24) fmtstring = ' '.join('{}{}'.format(abs(fw), 'x' if fw < 0 else 's') for fw in fieldwidths) # Convert Unicode input to bytes and decode result. unpack = struct.Struct(fmtstring).unpack_from # Alias. parse = lambda line: tuple(s.decode() for s in unpack(line.encode())) # Parse a sample line. line = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n' fields = parse(line) print('fields:', fields)</code>
输出:
fmtstring: '2s 10x 24s', record size: 36 chars fields: ('AB', 'MNOPQRSTUVWXYZ0123456789')
2.优化的字符串切片:
虽然字符串切片很常用,但对于大行来说它可能会变得很麻烦。这是一种优化方法:
<code class="python">from itertools import zip_longest from itertools import accumulate def make_parser(fieldwidths): # Calculate slice boundaries. cuts = tuple(cut for cut in accumulate(abs(fw) for fw in fieldwidths)) # Create field slice tuples. flds = tuple(zip_longest(cuts, (0,)+cuts))[:-1] # Ignore final value. # Construct the parsing function. parse = lambda line: tuple(line[i:j] for i, j in flds) 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 # Parse a sample line. line = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n' fieldwidths = (2, -10, 24) # Negative values indicate ignored padding fields. parse = make_parser(fieldwidths) fields = parse(line) print('fmtstring:', parse.fmtstring, ', record size:', parse.size, 'chars') print('fields:', fields)</code>
输出:
fmtstring: '2s 10x 24s', record size: 36 chars fields: ('AB', 'MNOPQRSTUVWXYZ0123456789')
以上是如何在Python中有效地解析固定宽度的文件行?的详细内容。更多信息请关注PHP中文网其他相关文章!