【问题标题】:Python code gets MemoryError in sl4aPython 代码在 sl4a 中获取 MemoryError
【发布时间】:2012-03-01 03:06:30
【问题描述】:

当我在 HTC Desire 上的 sl4a 中运行以下代码时出现 MemoryError:

def load_words():
    print "Loading word list from file..."
    inFile = open(words.txt, 'r', 0)
    wordlist = []
    for line in inFile:
        wordlist.append(line.strip())
    print "  ", len(wordlist), "words loaded.\n"
    return wordlist

打印“Loading word list from file...”后,它给出

Traceback (most recent call last):
    File "words.txt", line 92, in <module>
      wordlist = load_words()
    File "words.txt", line 29, in load_words
      for line in inFile:
MemoryError

顺便说一句,文件“words.txt”中有 83667 个英文单词,大小为 633.6 KB。帮助表示赞赏。 (代码是 MIT OpenCourseWare,CS 6.00 的一部分——计算机科学和编程入门,问题集 5,ps5_ghost.py)

这可能是 sl4a 中的错误吗?

[更新]: 我尝试了以下方法:

def load_words():
    print "Loading word list from file..."
    inFile = open(words.txt, 'r', 0)
    wordlist = []
    try:
        for line in inFile:
            wordlist.append(line.strip())
    except MemoryError:
        print 'Oops...'
    print "  ", len(wordlist), "words loaded.\n"
    return wordlist

然后,神奇地,我得到了

Loading word list from file...
Oops...
  83667 words loaded.

其余代码运行良好。有谁知道这是什么原因造成的?

【问题讨论】:

    标签: android python sl4a


    【解决方案1】:

    为这个问题 (Memory error due to the huge input file size) 提供的答案可能会有所帮助。以下内容改编自蒂姆对该问题的回答:

    wordlist = []
    with open("words.txt") as inFile:
        for line in inFile:
            wordlist.append(line.strip())
    

    此外,在调试方面,您可能希望删除 wordlist.append(line.strip()) 以尝试确定该行是否导致内存错误,或者(更有可能)打开文件中的每一行。

    【讨论】:

    • 感谢您的快速回复。我实际上尝试将print line 放在wordlist.append(line.strip()) 之前,并且打印了所有83667 个单词。另外,我的输入文件比那个 1.2GB 的怪物小得多……
    • @lllluuukke 在尝试打印加载的字数之前尝试inFile.close()? (使用 with open() 会为您关闭文件。)
    • 试过with open(),还是得到MemoryError
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多