我正在尝试导入一个单词列表来创建一个随机选择的简单单词游戏。并且得到TypeError的错误:'str'不支持缓冲区接口。我很欣赏有关我应该在代码中更改的建议。
# Hangman
#
# -----------------------------------
# Helper code
# List of words - TypeError: 'str' does not support the buffer interface, Python v.3.4
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print ("Loading word list from file...")
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = str.split(line)
print (" ", len(wordlist), "words loaded.")
return wordlist
def choose_word(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# end of helper code
# -----------------------------------
wordlist = load_words()
答案 0 :(得分:0)
根据您在评论中更新的追溯 -
回溯(最近一次调用最后一次):文件“/ ***** / Documents / LiClipse工作区/ python_test_LiClipse / first / init .py”,第65行,在wordlist = load_words()文件“/ ***** / Documents / LiClipse工作区/ python_test_LiClipse / first / init .py”,第41行,在load_words中打印(“从文件中加载单词列表...”)TypeError: 'str'不支持缓冲接口
在您的代码中的某处,您似乎正在使用 -
将'sys.stdout'重定向到文件sys.stdout = open('some_file','wb')
这应该是导致问题的原因,你应该打开你要将输出重定向到文本模式的文件,而不是二进制模式 -
sys.stdout = open('some_file','w')
虽然我几乎不怀疑你需要这个,如果你使用终端来运行程序你可以使用'>'在终端中运行程序时使用 - python script.py > some_file