gnacio的答案)是正确的,但是如果您使用32位进程,则可能会失败。
但是也许逐块读取文件然后计算
n每个块中的字符可能会很有用。
def blocks(files, size=65536): while True: b = files.read(size) if not b: break yield bwith open("file", "r") as f: print sum(bl.count("n") for bl in blocks(f))会做你的工作。
请注意,我没有以二进制形式打开文件,因此
rn将会转换为
n,从而使计数更加可靠。
对于Python 3,并使其更强大,以便读取具有各种字符的文件:
def blocks(files, size=65536): while True: b = files.read(size) if not b: break yield bwith open("file", "r",encoding="utf-8",errors='ignore') as f: print (sum(bl.count("n") for bl in blocks(f)))


