2012-09-13 49 views
1

我正在學習MIT公開課件上的CS/Python。他們希望我設計一個hang子手遊戲,並給了我一些初步的代碼,用於導入一個詞彙表並從那裏生成一個隨機詞。這段代碼自己返回一個錯誤:「不能有無緩衝的文本I/O」。下面的代碼:導入Wordlist

import random 
import string 

WORDLIST_FILENAME = "words.txt" 

def load_words(): 
    print("Loading word list from file...") 
    # inFile: file 
    inFile = open(WORDLIST_FILENAME, 'r', 0) 
    # line: string 
    line = inFile.readline() 
    # wordlist: list of strings 
    wordlist = string.split(line) 
    print(" ", len(wordlist), "words loaded.") 
    return wordlist 

def choose_word(wordlist): 
    return random.choice(wordlist) 

麻省理工學院的課程並不使用Python 3.0,這是我現在用的,所以有可能是一個問題都有;正如你所看到的,我已經從聲明更新了「打印」到一個與Python 3.0兼容的函數。

+0

請發佈完整的跟蹤:)你也應該避免使用字符串模塊,只需使用line.split()來代替。 – lolopop

+0

看來你可以找到完整的跟蹤.... [XKCD](http://forums.xkcd.com/viewtopic.php?f=20&t=72920) – sloth

+0

@BigYellowCactus很好找! –

回答

6

,因爲你想讀一個文本文件與緩衝這個錯誤被拋出關閉(第三個參數設置爲0):

inFile = open(WORDLIST_FILENAME, 'r', 0) 

inFile = open(WORDLIST_FILENAME, 'r') 
替換上面的行

,它應該工作。

從python文檔:

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer.

+0

錯誤消息實際上告訴你什麼是Python2-versus-3差異在這裏;只是你必須知道很多才能知道它告訴你什麼。與Python 2不同,Python 3不能執行無緩衝的文本文件,因爲「文本文件」現在意味着「文件解碼爲Unicode」,而不僅僅是「應用了新行轉換的文件」。 – abarnert

3

open內置函數調用刪除0。從python文檔:

Buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode).