在文件中获取TypeError但在shell中获得正确的答案

时间:2017-03-06 23:15:05

标签: python python-3.x file-io

我的代码如下:

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

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

2 个答案:

答案 0 :(得分:0)

基于回溯,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()

答案 1 :(得分:0)

我是个傻瓜 - 我有多行作为同一语句的一部分,但回溯只返回最后一行。 @ user2357112在我面前找到了它。 我修复之前的代码:

            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),这清除了输入问题。