2012-03-01 73 views
1

我的MemoryError當我在我的HTC Desire運行SL4A下面的代碼:Python的代碼的MemoryError在SL4A

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 

順便說一句,文件「words.txt」中有83667個英文單詞,大小633.6 KB。幫助讚賞。 (代碼是麻省理工學院開放式課程,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. 

而其餘代碼工作得很好。有誰知道這是什麼原因造成的?

回答

0

爲此問題提供的答案(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()),嘗試確定該行是否造成了內存錯誤,或(更可能)打開文件中的每一行。

+0

感謝您的快速回復。我實際上試圖在'wordlist.append(line.strip())'之前放置'print line',並且打印了所有83667個單詞。另外,我的輸入文件比1.2GB的怪物要小得多...... – lllluuukke 2012-03-01 04:27:51

+0

@lllluuukke在嘗試打印加載的字數之前,試試'inFile.close()'? (使用'with open()'爲你關閉文件。) – gary 2012-03-01 04:37:43

+0

嘗試了'open()',仍然有'MemoryError' – lllluuukke 2012-03-01 05:14:59