这个链接(How to get line count cheaply in Python?)有很多潜在的解决方案,但它们都忽略了一种使运行速度大大加快的方法,即使用无缓冲(raw)接口、使用bytearray和执行自己的缓冲。
使用一个经过修改的计时工具,我相信下面的代码比提供的任何解决方案都要快(稍微更像是pythonic):def _make_gen(reader):
b = reader(1024 * 1024)
while b:
yield b
b = reader(1024*1024)
def rawpycount(filename):
f = open(filename, 'rb')
f_gen = _make_gen(f.raw.read)
return sum( buf.count(b'\n') for buf in f_gen )
以下是我的时间安排:rawpycount 0.0048 0.0046 1.00
bufcount 0.0074 0.0066 1.43
wccount 0.01 0.01 2.17
itercount 0.014 0.014 3.04
opcount 0.021 0.02 4.43
kylecount 0.023 0.021 4.58
simplecount 0.022 0.022 4.81
mapcount 0.038 0.032 6.82
我会贴在那里,但我是一个相对新的用户堆栈交换,没有必要的甘露。
编辑:
这完全可以使用itertools的生成器表达式来完成,但是看起来很奇怪:from itertools import (takewhile,repeat)
def rawbigcount(filename):
f = open(filename, 'rb')
bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None)))
return sum( buf.count(b'\n') for buf in bufgen if buf )