<p>由于您的数据在固定宽度记录中显示为固定宽度字段,因此可以使用<code>struct</code>模块将每一行快速分解为单独的字段。你知道吗</p>
<p>当您只需要处理其中一个字段时,解析每一行的所有字段可能会过于繁琐,但我所用的方法说明了在您需要进行其他处理时是如何完成的,并且使用<code>struct</code>模块在任何情况下都会相对快速。你知道吗</p>
<p>假设输入文件只包含以下数据行:</p>
<pre class="lang-none prettyprint-override"><code>ATOM 139 C1 DPPC 18 17.250 58.420 10.850 1.00 0.00
ATOM 139 C1 DPPC 18 17.250 58.420 10.850 1.00 0.00
ATOM 139 C1 DPPC 18 17.250 58.420 10.850 1.00 0.00
ATOM 139 C1 DPPC 18 17.250 58.420 10.850 1.00 0.00
ATOM 139 C1 DPPC 18 17.250 58.420 10.850 1.00 0.00
ATOM 139 C1 DPPC 18 17.250 58.420 10.850 1.00 0.00
ATOM 139 C1 DPPC 18 17.250 58.420 10.850 1.00 0.00
ATOM 139 C1 DPPC 18 17.250 58.420 10.850 1.00 0.00
ATOM 139 C1 DPPC 18 17.250 58.420 10.850 1.00 0.00
ATOM 189 C1 DPPC 19 23.050 20.800 11.000 1.00 0.00
ATOM 189 C1 DPPC 19 23.050 20.800 11.000 1.00 0.00
ATOM 189 C1 DPPC 19 23.050 20.800 11.000 1.00 0.00
ATOM 189 C1 DPPC 19 23.050 20.800 11.000 1.00 0.00
ATOM 189 C1 DPPC 19 23.050 20.800 11.000 1.00 0.00
ATOM 189 C1 DPPC 19 23.050 20.800 11.000 1.00 0.00
ATOM 189 C1 DPPC 19 23.050 20.800 11.000 1.00 0.00
ATOM 189 C1 DPPC 20 23.050 20.800 11.000 1.00 0.00
ATOM 189 C1 DPPC 20 23.050 20.800 11.000 1.00 0.00
ATOM 189 C1 DPPC 20 23.050 20.800 11.000 1.00 0.00
</code></pre>
<p>您所需要做的就是记住前一行中字段的值,以便将其与当前字段进行比较。要开始这个过程,必须分别读取和解析第一行,因此有一个<code>prev</code>值要与后面的行进行比较。还要注意,第5个字段是由<code>[4]</code>索引的字段,因为第一个字段从<code>[0]</code>开始。你知道吗</p>
<pre><code>import struct
# negative widths represent ignored padding fields
fieldwidths = 4, -4, 3, -2, 2, -2, 4, -3, 2, -6, 6, -2, 6, -2, 6, -2, 4, -2, 4
fmtstring = ' '.join('{}{}'.format(abs(fw), 'x' if fw < 0 else 's')
for fw in fieldwidths)
fieldstruct = struct.Struct(fmtstring)
parse = fieldstruct.unpack_from # a function to split line up into fields
with open('test_file.pdb') as f1:
prev = parse(next(f1))[4] # remember value of fifth field
cnt = 1
for line in f1:
curr = parse(line)[4] # get value of fifth field
if curr == prev: # same as last one?
cnt += 1
else:
print('{} occurred {} times'.format(prev, cnt))
prev = curr
cnt = 1
print('{} occurred {} times'.format(prev, cnt)) # for last line
</code></pre>
<p>输出:</p>
<pre class="lang-none prettyprint-override"><code>18 occurred 9 times
19 occurred 7 times
20 occurred 3 times
</code></pre>