这是一个用正则表达式分隔的块中迭代文件的方法
图案。这可能比这里需要的要强大一点;正则表达式
模式仅仅是'\n{2,}',即两个或多个行尾字符。在
另一方面,一旦你有了这个工具,就没有必要重新发明轮子了。
一旦你有了一个块——一个代表数组的多行字符串——你可以
用np.loadtxt 解析它并使用diagonals 函数找到所有对角线:
import io
import re
import numpy as np
# http://stackoverflow.com/q/17508697/190597
def open_chunk(readfunc, delimiter, chunksize=1024):
"""
readfunc(chunksize) should return a string.
"""
remainder = ''
for chunk in iter(lambda: readfunc(chunksize), ''):
pieces = re.split(delimiter, remainder + chunk)
for piece in pieces[:-1]:
yield piece
remainder = pieces[-1]
if remainder:
yield remainder
# Based on http://stackoverflow.com/a/6313407/190597
def diagonals(L):
h, w = len(L), len(L[0])
return [[L[h - p + q - 1][q]
for q in range(max(p-h+1,0), min(p+1, w))]
for p in range(h + w - 1) ]
with open('data', 'r') as f:
for chunk in open_chunk(f.read, r'\n{2,}'):
arr = np.loadtxt(io.BytesIO(chunk))
print([d for d in diagonals(arr) if len(d) != 1])
产量
[[1.0, 2.0], [1.0, 1.0, 2.0], [2.0, 1.0]]
[[3.0, 2.0], [3.0, 2.0]]
[[3.0, 2.0], [2.0, 2.0]]