You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hangman项目随机取词报错IndexError:string index out of range求助

Hangman项目随机选单词触发IndexError问题

我在开发Hangman(猜单词)项目时,尝试从文件中随机选取单词,却出现IndexError: string index out of range错误,以下是我的代码及完整报错栈:

代码

import random

WORDLIST_FILENAME = "C:/Users/14237/Downloads/softwear/words.txt"

def loadWords():
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def chooseWord(wordlist):
    return random.choice(wordlist)

--------------------------------------
def hangman(secretWord):
    guesses = 8
    lettersGuessed = []
    print("Welcome to the game, Hangman!")
    print("I am thinking of a word that is", str(len(secretWord)), "letters long.")
    while True:
        print("-------------")
        print("You have", guesses, "guesses left.")
        print("Available letters:", getAvailableLetters(lettersGuessed))
        userGuess = input("Please guess a letter: ")
        userGuess = userGuess.lower()
    if userGuess in lettersGuessed:
        print("Oops! You've already guessed that letter:", getGuessedWord(secretWord, lettersGuessed))
    elif userGuess in secretWord:        
        lettersGuessed.append(userGuess)
        print("That is correct!:", getGuessedWord(secretWord, lettersGuessed))
    else:
        guesses -= 1
        lettersGuessed.append(userGuess)
        print("Sorry, that letter was not correct:", getGuessedWord(secretWord, lettersGuessed))
    if guesses == 0:
        print("-------------")
        print("Sorry, you ran out of guesses. The word was", secretWord + ".")
    elif isWordGuessed(secretWord, lettersGuessed) == True:
        print("------------")
        print("Congratulations, you won!")
secretWord = chooseWord(wordlist)
hangman(secretWord)

报错栈

IndexError                                Traceback (most recent call last) Input In [74], in <cell line: 27>()
         25         print("------------")
         26         print("Congratulations, you won!")
    ---> 27 secretWord = chooseWord(wordlist)
         28 hangman(secretWord)
    
    Input In [68], in chooseWord(wordlist)
         16 def chooseWord(wordlist):
    ---> 17     return random.choice(wordlist)
    
    File ~\anaconda3\lib\random.py:346, in Random.choice(self, seq)
        344 """Choose a random element from a non-empty sequence."""
        345 # raises IndexError if seq is empty
    ---> 346 return seq[self._randbelow(len(seq))]
    
IndexError: string index out of range

错误原因及修复方法

核心原因

  1. 未初始化wordlist变量:定义了loadWords()函数加载单词列表,但从未调用它给wordlist赋值。当前wordlist要么未定义(理论上触发NameError),要么被错误赋值为空字符串/无效字符串,导致random.choice()将其当作字符串处理,触发索引越界。
  2. 单词文件读取不完整:inFile.readline()仅读取文件第一行,若单词分布在多行会遗漏内容;若第一行是空的,wordlist会变成空列表,也会引发错误。
  3. hangman函数缩进错误:while True循环后的判断逻辑未缩进,导致循环无限空转,永远不会执行猜字母的核心逻辑。

修复步骤

  1. 初始化单词列表:在调用chooseWord()前,必须调用loadWords()获取正确的单词列表:
    # 在secretWord = chooseWord(wordlist)前添加
    wordlist = loadWords()
    
  2. 修复文件读取逻辑:改为读取整个文件内容,确保获取所有单词,同时用with语句自动管理文件句柄:
    def loadWords():
        print("Loading word list from file...")
        with open(WORDLIST_FILENAME, 'r') as inFile:
            wordlist = inFile.read().split()
        print("  ", len(wordlist), "words loaded.")
        return wordlist
    
  3. 修复hangman函数缩进:将循环内的所有逻辑代码缩进,同时添加break退出循环:
    def hangman(secretWord):
        guesses = 8
        lettersGuessed = []
        print("Welcome to the game, Hangman!")
        print("I am thinking of a word that is", str(len(secretWord)), "letters long.")
        while True:
            print("-------------")
            print("You have", guesses, "guesses left.")
            print("Available letters:", getAvailableLetters(lettersGuessed))
            userGuess = input("Please guess a letter: ")
            userGuess = userGuess.lower()
            
            if userGuess in lettersGuessed:
                print("Oops! You've already guessed that letter:", getGuessedWord(secretWord, lettersGuessed))
            elif userGuess in secretWord:        
                lettersGuessed.append(userGuess)
                print("That is correct!:", getGuessedWord(secretWord, lettersGuessed))
            else:
                guesses -= 1
                lettersGuessed.append(userGuess)
                print("Sorry, that letter was not correct:", getGuessedWord(secretWord, lettersGuessed))
            
            if guesses == 0:
                print("-------------")
                print("Sorry, you ran out of guesses. The word was", secretWord + ".")
                break
            elif isWordGuessed(secretWord, lettersGuessed):
                print("------------")
                print("Congratulations, you won!")
                break
    

内容的提问来源于stack exchange,提问作者Sonicpsycho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 18:55:23