Python代码在sl4a中获取MemoryError

时间:2012-03-01 03:06:30

标签: android python sl4a

当我在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

在打印“从文件中加载单词列表...”后,它会显示

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
BTW,文件“words.txt”中有83667个英文单词,大小633.6 KB。帮助赞赏。 (该代码是MIT OpenCourseWare的一部分,CS 6.00 - 计算机科学和编程入门,问题集5,ps5_ghost.py)

这可能是sl4a中的错误吗?

[UPDATE]: 我尝试了以下方法:

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.

其余代码运行正常。有谁知道是什么造成的?

1 个答案:

答案 0 :(得分:0)

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

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

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