【问题标题】:How to manage memory error in python?如何管理python中的内存错误?
【发布时间】:2014-02-11 12:08:25
【问题描述】:

这是我的代码,用于计算频率

import collections
import codecs
import io
from collections import Counter
with io.open('Combine.txt', 'r', encoding='utf8') as infh:
    words =infh.read().split()
    with open('Counts2.txt', 'wb') as f:
        for word, count in Counter(words).most_common(100000000):
            f.write(u'{} {}\n'.format(word, count).encode('utf-8')) 

当我尝试读取一个大文件(4 GB)时出现错误

Traceback (most recent call last):
  File "counter.py", line 7, in <module>
    words =infh.read().split()
  File "/usr/lib/python2.7/codecs.py", line 296, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
MemoryError

我使用的是 Ubuntu 12.4,8 GB RAM Intel Core i7 如何解决此错误? /

usr/lib/python2.7/codecs.py", line 296, in decode
        (result, consumed) = self._buffer_decode(data, self.errors, final)
    MemoryError

【问题讨论】:

标签: python file python-2.7


【解决方案1】:

这是逐行处理文件的pythonic方式:

with open(...) as fh:
    for line in fh:
        pass

这将负责打开和关闭文件,包括是否在内部块中引发异常,此外它会将文件对象 fh 视为可迭代对象,它会自动使用缓冲 I/O 并管理内存,因此您不必担心大文件。

【讨论】:

  • 如果所有单词都在一行怎么办?
  • 这应该是微不足道的:a)通过你的shell将它转换为每行一个单词或b)从块中读取文件(即手动管理内存)并进行相应的处理。
  • @MichaelFoukarakis 错误位于 usr/lib/python2.7/codecs.py",第 296 行,在 decode (result, used) = self._buffer_decode(data, self.errors, final) MemoryError
【解决方案2】:

用 readline 代替 read() 怎么样

http://docs.python.org/2/tutorial/inputoutput.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多