gpt4 book ai didi

python - 导入词汇表

转载 作者:太空宇宙 更新时间:2023-11-04 07:10:42 25 4
gpt4 key购买 nike

我正在麻省理工学院的开放课件上学习 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.

关于python - 导入词汇表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12412882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com