获取文件中的TypeError,但sh中的答案正确

2024-04-19 12:10:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码如下:

def randword():
    #american-english-small can be replaced with american-english[-large|-huge]
    DICT = open('/usr/share/dict/american-english-small', 'r')
    length = len(DICT.readlines())
    print(length)
    randline = randint(1, length)
    print(randline) 
    word = DICT.readline(randline)
    print(word)
    DICT.close()
    return word
    #return DICT.readline(randint(1, len(DICT.readlines())))

最后的一行是我的原始代码,其余的是我把它拆开来找出问题所在。在我的终端,一切都是正确的:

>>> DICT = open('/usr/share/dict/american-english-small', 'r')
>>> word = DICT.readline(46957)
>>> print(word)
AIDS's

但是,当我运行文件时,在查找行和读取行之间出现错误:

51175
18132

运行时错误的回溯:

 +---+
 |   |
 O   |
/|\  |
/ \  |
     |
==========

Incorrect guesses: a b c d e f 

Traceback (most recent call last):
  File "/home/joshua/Documents/Coding/Python/hangman.py", line 123, in     <module>
    main()
  File "/home/joshua/Documents/Coding/Python/hangman.py", line 117, in main
    "\nThe word was " + secretWord + ".")
TypeError: Can't convert 'int' object to str implicitly

知道我做错了什么吗?提前谢谢


Tags: 代码sharereadlinelenenglishusropenlength
2条回答

根据回溯,secretWord是一个整数而不是字符串:

"\nThe word was " + secretWord + ".")
TypeError: Can't convert 'int' object to str implicitly

在没有看到其他代码分配secretWord的情况下,我的猜测是secretWord是列表或字典的索引,您应该执行以下操作

"\n`enter code here`The word was " + wordcontainer[secretWord] + "."

其中wordcontainer是单词列表或字典

编辑

也有可能你只是碰巧随机地画了一个页码或者类似的东西,它是你文档的一部分,所以当你从文档中读入一行时,它会被作为一个整数读入。在这种情况下,您要么需要处理这种可能性,要么可以考虑使用一个已有的单词列表,该列表已经是一个不错的Python格式

from nltk.corpus import words #You will need to use nltk.download() to download this in addition to using pip to install the package.
wordlist = words.words()

我是个傻瓜-我有多行作为同一语句的一部分,但回溯只返回最后一行@用户2357112在我之前就知道了。 在我修复代码之前:

            print("You've run out of guesses. \nYou had " + len(errors) +
              " errors and " + len(correctGuesses) + " correct guesses. " +
              "\nThe word was " + secretWord + ".")

之后:

            print("You've run out of guesses. \nYou had " + str(len(errors)) +
              " errors and " + str(len(correctGuesses)) + " correct guesses. " +
              "\nThe word was " + secretWord + ".")

向@juanpa.arrivillaga大喊大叫,感谢他帮我解决了我原以为有的问题;我将readline(n)切换到linecahce.getline(n),这就解决了我的输入问题

相关问题 更多 >