读取6.9GB的文件会导致段错误



我试图打开最新的日语维基百科数据库在Linux上的Python 3.3.1阅读,但我得到一个Segmentation fault (core dumped)错误与这个短程序:

with open("jawiki-latest-pages-articles.xml") as f:
    text = f.read()

文件本身相当大:

-rw-r--r-- 1 fredrick users 7368183805 May 17 20:19 jawiki-latest-pages-articles.xml

所以看起来我可以存储的字符串的长度是有上限的。解决这种情况的最好方法是什么?

我的最终目标是计算文件中最常见的字符,有点像Jack Halpern的"报纸中最常用的汉字"的现代版本。:)

不要一下子读完整篇文章。即使您的Python发行版被编译为64位程序(在32位程序中分配超过4 GB的虚拟内存是根本不可能的),并且即使您有足够的RAM来存储所有内容,一次将所有内容读入内存仍然是一个坏主意。

一个简单的选择是一次读取一行并处理每一行:

with open("jawiki-latest-pages-articles.xml") as f:
    for line in f:
        # Process one line

或者,您可以在固定大小的块中处理它:

while True:
    data = f.read(65536)  # Or any other reasonable-sized chunk
    if not data:
        break
    # Process one chunk of data.  Make sure to handle data which overlaps
    # between chunks properly, and make sure to handle EOF properly

这是我最终使用的程序,如果有人好奇的话。

from collections import Counter
counter = Counter()
progress = 0
with open("jawiki-latest-pages-articles.xml") as f:
    for line in f:
        progress += 1
        counter.update(line)
        if not progress%10000: print("Processing line {0}..., number {1}".format(line[:10], progress))
output = open("output.txt", "w+")
for k, v in counter.items():
    print("{0}t{1}".format(k, v), file=output)
output.close()

最新更新