Python 字符串正在变异为字典,但可以';我不知道在哪里

Python 字符串正在变异为字典,但可以';我不知道在哪里,python,string,dictionary,semantics,Python,String,Dictionary,Semantics,我正在尝试实现一个拼字游戏,playHand函数返回一个AttributeError:“str”对象没有属性“copy”。这个错误来自updateHand=Hand.copy(),但我已经单独测试了updateHand,并且在其运行中运行良好。我试着查了一下,但没有找到任何东西。抱歉这么长时间!我情不自禁。谢谢 VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 SCRABBLE_LETTER_VALUES =

我正在尝试实现一个拼字游戏,playHand函数返回一个AttributeError:“str”对象没有属性“copy”。这个错误来自updateHand=Hand.copy(),但我已经单独测试了updateHand,并且在其运行中运行良好。我试着查了一下,但没有找到任何东西。抱歉这么长时间!我情不自禁。谢谢

VOWELS = 'aeiou'
CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
HAND_SIZE = 7

SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}

def getWordScore(word, n):
"""
Returns the score for a word. Assumes the word is a valid word.

The score for a word is the sum of the points for letters in the
word, multiplied by the length of the word, PLUS 50 points if all n
letters are used on the first turn.

Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is
worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)

word: string (lowercase letters)
n: integer (HAND_SIZE; i.e., hand size required for additional points)
returns: int >= 0
"""
score = 0

for letter in word:
    score += SCRABBLE_LETTER_VALUES[letter]

return score * len(word) + 50 * (len(word) == n)

def displayHand(hand):
"""
Displays the letters currently in the hand.

For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
   a x x l l l e
The order of the letters is unimportant.

hand: dictionary (string -> int)
"""
for letter in hand.keys():
    for j in range(hand[letter]):
         print(letter,end=" ")       # print all on the same line
print()                             # print an empty line


def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it. 

Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.

Has no side effects: does not modify hand.

word: string
hand: dictionary (string -> int)    
returns: dictionary (string -> int)
"""

Hand = hand.copy()

for letter in word:
    Hand[letter] -= 1

return Hand



def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.

Does not mutate hand or wordList.

word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
Hand = hand.copy()

if word not in wordList:
    return False

for letter in word:
    if letter not in Hand:
        return(False)   
        break
    else: 
        Hand[letter] -= 1  
        if Hand[letter] < 0:
            return False
return True    

def calculateHandlen(hand):
""" 
Returns the length (number of letters) in the current hand.

hand: dictionary (string int)
returns: integer
"""
return sum(hand.values())

def printCurrentHand(hand):
print('Current Hand: ', end = ' ')
displayHand(hand)

def printTotalScore(score):
print('Total: ' + str(score) + ' points')

def updateAndPrintScore(score, word, n):
currentScore = getWordScore(word, n)
score += currentScore
print('" ' + word + ' "' + ' earned ' + str(currentScore) + ' points.', end             = ' ')
print(printTotalScore(score))    

return score


def playHand(hand, wordList, n):
"""
Allows the user to play the given hand, as follows:

* The hand is displayed.
* The user may input a word or a single period (the string ".") 
  to indicate they're done playing
* Invalid words are rejected, and a message is displayed asking
  the user to choose another word until they enter a valid word or "."
* When a valid word is entered, it uses up letters from the hand.
* After every valid word: the score for that word is displayed,
  the remaining letters in the hand are displayed, and the user
  is asked to input another word.
* The sum of the word scores is displayed when the hand finishes.
* The hand finishes when there are no more unused letters or the user
  inputs a "."

  hand: dictionary (string -> int)
  wordList: list of lowercase strings
  n: integer (HAND_SIZE; i.e., hand size required for additional points)

"""
score = 0# Keep track of the total score
hand_copy = hand.copy()

while calculateHandlen(hand_copy) > 0:
    printCurrentHand(hand_copy)
    word = input("Enter word, or a \".\" to indicate that you are finished: ")

    if word == '.':
        print("Goodbye!", end = ' ')
        break

    if isValidWord(word, hand_copy, wordList):
        score += updateAndPrintScore(score, word, n)
        hand_copy = updateHand(word, hand_copy)

    else: 
        print('Invalid word!')
        print()

if calculateHandlen(hand_copy) == 0:
    print("Run out of letters.", end = ' ')

printTotalScore(score)      

playHand({'h':1, 'i':1, 'c':1, 'z':1, 'm':2, 'a':1},['him', 'cam'], 7)
元音='aeiou'
辅音='bcdfghjklmnpnpqrstvwxyz'
手部尺寸=7
拼字字母值={
“a”:1,'b':3,'c':3,'d':2,'e':1,'f':4,'g':2,'h':4,'i':1,'j':8,'k':5,'l':1,'m':3,'n':1,'o':1,'p':3,'q':10,'r':1,'s':1,'t':1,'u':1,'v':4,'w':4,'x':8,'y':4,'z':10
}
def getWordScore(单词,n):
"""
返回单词的分数。假定该单词是有效单词。
单词的分数是单词中字母的分数之和
单词,乘以单词的长度,如果全部为n,则加50分
字母在第一次转弯时使用。
字母在拼字游戏中被打分;A值1,B值3,C值1
值3,D值2,E值1,依此类推(请参见拼字字母值)
单词:字符串(小写字母)
n:整数(手部尺寸;即额外点所需的手部尺寸)
返回:int>=0
"""
分数=0
对于大写字母:
分数+=拼字字母值[字母]
返回分数*len(word)+50*(len(word)==n)
def displayHand(手动):
"""
显示当前手上的字母。
例如:
>>>displayHand({'a':1,'x':2,'l':3,'e':1})
应该打印出如下内容:
a x l l e
字母的顺序不重要。
手:字典(字符串->整数)
"""
对于手上的字母。键():
对于范围内的j(手写[字母]):
打印(字母,end=“”)#在同一行上打印所有内容
打印()#打印空行
def updateHand(手,字):
"""
假设“手”包含单词中的所有字母。
换言之,这假设
“word”、“hand”中出现的字母至少有
那封信中有很多是我写的。
更新手:使用给定单词中的字母
并返回新的手,没有这些字母。
没有副作用:不修改手。
字:字符串
手:字典(字符串->整数)
返回:字典(字符串->整型)
"""
Hand=Hand.copy()
对于大写字母:
手写[字母]-=1
回手
def isValidWord(字、手、字表):
"""
如果单词在单词列表中且完全为空,则返回True
由手中的字母组成。否则,返回False。
不会变异hand或wordList。
字:字符串
手:字典(字符串->整数)
wordList:小写字符串列表
"""
Hand=Hand.copy()
如果单词不在单词列表中:
返回错误
对于大写字母:
如果未收到信函:
返回(假)
打破
其他:
手写[字母]-=1
如果手写[字母]<0:
返回错误
返回真值
def calculateHandlen(手动):
""" 
返回当前手的长度(字母数)。
手:字典(字符串int)
返回:整数
"""
返回和(hand.values())
def printCurrentHand(手动):
打印('当前手:',结束='')
显示手(手)
def printTotalScore(分数):
打印('Total:'+str(分数)+'points')
def updateAndPrintScore(分数,字,n):
currentScore=getWordScore(单词,n)
分数+=当前分数
打印(““+word+”“+”已赚“+str(currentScore)+”分“,”结束=”)
打印(打印总分数(分数))
回击得分
def playHand(手动,单词列表,n):
"""
允许用户播放给定的手牌,如下所示:
*显示手。
*用户可以输入单词或单个句点(字符串“.”)
表明他们已经玩完了
*无效单词将被拒绝,并显示一条询问的消息
用户必须选择另一个单词,直到输入有效的单词或“”
*当输入一个有效的单词时,它会用完手上的字母。
*在每个有效单词之后:显示该单词的分数,
将显示手上剩余的字母,用户
要求输入另一个单词。
*当手完成时,将显示单词分数的总和。
*当不再有未使用的字母或用户时,手动结束
输入“a”
手:字典(字符串->整数)
wordList:小写字符串列表
n:整数(手部尺寸;即额外点所需的手部尺寸)
"""
分数=0#记录总分
hand\u copy=hand.copy()
当计算Handlen(手抄本)>0时:
printCurrentHand(手抄本)
word=输入(“输入word,或一个\”“\”,表示您已完成:)
如果单词=='。:
打印(“再见!”,结束=“”)
打破
如果是有效文字(文字、手印、字表):
分数+=更新的数据点分数(分数,单词,n)
hand\u copy=updateHand(word,hand\u copy)
其他:
打印('无效单词!')
打印()
如果calculateHandlen(手抄本)==0:
打印(“字母用完”,结束=“”)
printTotalScore(分数)
游戏手({'h':1,'i':1,'c':1,'z':1,'m':2,'a':1},['him','cam',7)
错误代码

runfile('C:/Users/.spyder2-py3/ProjectsMIT/temp.py',wdir='C:/Users/.spyder2-py3/ProjectsMIT')
当前手:c a h i m z
输入word或“.”表示您已完成:他
“他”得了24分。总计:24分
没有一个
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
运行文件('C:/Users/.spyder2-py3/ProjectsMIT/temp.py',wdir='C:/Users/.spyder2-py3/ProjectsMIT')
文件“C:\Users\Anaconda3\lib\site packages\spyderlib\widgets\externalshell\sitecustomize.py”,第714行,在runfile中
execfile(文件名、命名空间)
文件“C:\Users\Anaconda3\lib\site packages\spyderlib\widgets\externalshell\sitecustomize.py”,第89行,在execfile中
exec(编译(f.read(),文件名,'exec'),命名空间)
第183行,在
游戏手({'h':1,'i':1,'c':1,'z':1,'m':2,'a':1},['him','cam',7)
第172行,在playHand中
hand\u copy=updateHand(word,hand\u copy)
第72行,在updateHand中
Hand=Hand.copy()
runfile('C:/Users/.spyder2-py3/ProjectsMIT/temp.py', wdir='C:/Users/.spyder2-py3/ProjectsMIT')
Current Hand:  c a h i m m z 

Enter word, or a "." to indicate that you are finished: him
" him " earned 24 points. Total: 24 points
None
Traceback (most recent call last):

  File "<ipython-input-2-2e4e8585ae85>", line 1, in <module>
    runfile('C:/Users/.spyder2-py3/ProjectsMIT/temp.py', wdir='C:/Users/.spyder2-py3/ProjectsMIT')

  File "C:\Users\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
    execfile(filename, namespace)

  File "C:\Users\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

    line 183, in <module>
    playHand({'h':1, 'i':1, 'c':1, 'z':1, 'm':2, 'a':1},['him', 'cam'], 7)

    line 172, in playHand
    hand_copy = updateHand(word, hand_copy)

   line 72, in updateHand
    Hand = hand.copy()

AttributeError: 'str' object has no attribute 'copy'
hand_copy = updateHand(word, hand_copy)
def updateHand(hand, word):
hand_copy = updateHand(hand_copy, word)