Python 3:TypeError:Type str不支持缓冲区API [英] Python 3 : TypeError: Type str doesn't support the buffer API

查看:129
本文介绍了Python 3:TypeError:Type str不支持缓冲区API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到错误:


TypeError:类型str不支持缓冲区API


当尝试运行以下代码时:

 导入随机
导入字符串

WORDLIST_FILENAME = words.txt

def loadWords():

返回有效列表单词是小写字母的字符串。

根据单词列表的大小,此功能可能需要
才能完成。

打印(正在从文件中加载单词列表...)
#inFile:文件
inFile = open(WORDLIST_FILENAME,'rb',0)
#行:字符串
行= inFile.readline()
#wordlist:字符串列表
wordlist = line.split()
print(,len(wordlist),加载的单词。)
返回单词列表

def selectWord(单词列表):

单词列表(列表):单词列表(字符串)

返回aw从wordlist中随机发出的命令

返回random.choice(wordlist)

#辅助代码的结尾
#--------- --------------------------

#将单词列表加载到变量单词列表
#so可以从程序中的任何位置访问它
wordlist = loadWords()

def isWordGuessed(secretWord,LettersGuessed):
'''
secretWord:字符串,用户正在猜测
个字母的单词Guessed:列表,到目前为止已经猜到了哪些字母
返回:布尔值,如果所有secretWord的字母都在letterGuessed中则为True;
错误,否则
'''

for x in secretWord:
如果x不以字母进行猜测:
返回False
返回True



def getGuessedWord(secretWord,LettersGuessed):
'''
secretWord:字符串,用户猜测
个字母的单词Guessed:列表,到目前为止,已经猜出了哪些字母
返回:字符串,由字母和下划线组成,表示
secretWord中到目前为止已经猜出了哪些字母。
'''

guessedWord = ['_'] * len(secretWord)
for x in lettersGuessed:
## 1 **查找x的出现在secretWord中
出现次数= [] i,j中的
枚举(secretWord):如果j == x:

出现次数。append(i)
## 2 *转到guessedWord中的相同索引,并为出现的i用x
替换它们:
guessedWord [i] = x;

return''.join(guessedWord)



def getAvailableLetters(lettersGuessed):

'''
lettersGuessed:列表,到目前为止已猜出的字母
返回:字符串,由字母组成,表示尚未猜到的字母

'''

available_Letters = []
all_letters = list(string.ascii_lowercase)
在all_letters中为x:
如果(x不在字母中) ):
available_Letters.append(x)
return''.join(available_Letters)


def hangman(secretWord):
'''
secretWord:字符串,要猜测的秘密单词。

启动Hangman的互动游戏。

*在游戏开始时,让用户知道secretWord包含多少个
个字母。

*要求用户每轮提供一个猜测(即字母)。

*用户在每次猜测
后应立即收到有关其猜测是否出现在计算机单词中的反馈。

*每一轮之后,您还应该向用户显示到目前为止部分猜测的
单词以及
用户尚未猜测的字母。

遵循问题记录中详述的其他限制。
'''

print(欢迎来到游戏中,Hang子手!)
print(我在想一个长4个字母的单词。)
number_of_guesses = 8个
个字母,猜测为[]
而True时:
print( ----------------------- ---------)
打印(您有,number_of_guesses,左!)
打印(可用字母:,getAvailableLetters(lettersGuessed))
print(请猜一个字母:)
guess = input()

而True:
print(请猜一个字母:)
在字母中猜测:
print(糟糕!您已经猜到了该字母:,getGuessedWord(secretWord,lettersGuessed))
中断
其他:
if(猜测word中的猜测) :
letterGuessed.append(guess)
print( Goodgues:,getGuessedWord(secretWord,le ttersGuessed))
else:
number_of_guesses- = 1


print( ------------------ ---------------)
if(number_of_guesses == 0):
print(抱歉,您用完了所有的猜测。这个词是别的。 )
打破
if(isWordGuessed(secretWord,letterGuessed)):
print(恭喜,您赢了!)
打破


secretWord = selectWord(wordlist).lower()
hangman(secretWord)

the导致错误的行是:

  if(guess in secretWord):

此行是什么问题?



此处是到word.txt的链接,如果您想在自己的计算机上运行代码

解决方案

您使用'rb将单词作为二进制数据加载打开文件时使用'模式:

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

然后尝试查看该二进制数据中是否包含字符串:

  if(猜测秘密):

如果 WORDLIST_FILENAME 是文本,请不要不要使用二进制模式读取它。使用文本模式:

  inFile = open(WORDLIST_FILENAME,'r',encoding ='ascii')

您链接的文件是一个简单的ASCII编码文件,因此我使用该编解码器将其解码为Unicode字符串。 / p>

I'm getting the error :

TypeError: Type str doesn't support the buffer API

when trying to run the following code :

import random
import string

WORDLIST_FILENAME = "words.txt"

def loadWords():
    """
    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, 'rb', 0)
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print ("  ", len(wordlist), "words loaded.")
    return wordlist

def chooseWord(wordlist):
    """
    wordlist (list): list of words (strings)

    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code
# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''

    for x in secretWord :
        if x not in lettersGuessed :
            return False
    return True



def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''

    guessedWord=['_']*len(secretWord)
    for x in lettersGuessed :
##      1**   find the occurences of x in secretWord
        occurences = []
        for i, j in enumerate(secretWord):
             if j == x:
                occurences.append(i)
##      2* go to the same indices in guessedWord and replace them by x 
        for i in occurences :
            guessedWord[i]=x;

    return ''.join(guessedWord)



def getAvailableLetters(lettersGuessed):

    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''

    available_Letters=[]
    all_letters=list(string.ascii_lowercase)
    for x in all_letters :
         if (x not in lettersGuessed):
             available_Letters.append(x)
    return ''.join(available_Letters)


def hangman(secretWord):
    '''
    secretWord: string, the secret word to guess.

    Starts up an interactive game of Hangman.

    * At the start of the game, let the user know how many 
      letters the secretWord contains.

    * Ask the user to supply one guess (i.e. letter) per round.

    * The user should receive feedback immediately after each guess 
      about whether their guess appears in the computers word.

    * After each round, you should also display to the user the 
      partially guessed word so far, as well as letters that the 
      user has not yet guessed.

    Follows the other limitations detailed in the problem write-up.
    '''

    print(" Welcome to the game, Hangman!")
    print("I am thinking of a word that is 4 letters long.")
    number_of_guesses = 8
    lettersGuessed = []
    while True :
        print("--------------------------------")
        print ("You have " , number_of_guesses , "left !")
        print("Available letters : " , getAvailableLetters(lettersGuessed) )
        print("Please guess a letter : ")
        guess = input()

        while True:
                print("Please guess a letter : ")
                if guess in lettersGuessed:
                    print("Oops ! you've already guessed that letter :" , getGuessedWord(secretWord, lettersGuessed))
                    break 
                else :
                    if(guess in secretWord ) :
                        lettersGuessed.append(guess)
                        print("Good guess:", getGuessedWord(secretWord, lettersGuessed) )
                    else :
                        number_of_guesses-=1


        print("---------------------------------")
        if(number_of_guesses == 0) :
            print(" Sorry, you ran out of guesses. The word was else. ")
            break
        if(isWordGuessed(secretWord, lettersGuessed)):
            print(" Congratulations, you won!")
            break


secretWord = chooseWord(wordlist).lower()
hangman(secretWord)

the line that is causing the error is :

if(guess in secretWord ) :  

What is the problem with this line ?

here is a link to words.txt if you want to run the code on your own machine

解决方案

You loaded your words as binary data, by using the 'rb' mode when opening the file:

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

then tried to see if a string is contained in that binary data:

if(guess in secretWord ) :

If WORDLIST_FILENAME is text, don't use binary mode to read it. Use a text mode:

inFile = open(WORDLIST_FILENAME, 'r', encoding='ascii')

The file you linked is a simple ASCII-encoded file, so I used that codec to decode it to a Unicode string.

这篇关于Python 3:TypeError:Type str不支持缓冲区API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆