Skip to main content
 首页 » 编程设计

python之导入词汇表

2025年05月04日11落叶无声

我正在麻省理工学院的开放课件上学习 CS/Python。他们要我设计一个刽子手游戏,并给了我一些初步代码,用于导入单词列表并从中生成随机单词。此代码本身会返回一个错误:“不能有无缓冲的文本 I/O。”这是代码:

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) 

MIT类(class)没有使用Python 3.0,我用的是Python 3.0,所以可能那里有问题;如您所见,为了与 Python 3.0 兼容,我已经将“print”从声明更新为函数。

请您参考如下方法:

抛出这个错误是因为你试图在关闭缓冲(第三个参数设置为 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.