0

我是编程和 python 的新手。我在网上寻求帮助,我按照他们说的做,但我认为我犯了一个我无法理解的错误。现在我在这里要做的就是:如果单词与用户输入的长度与文件中的单词匹配,则列出这些单词。如果我userLength用实际数字替换它有点工作,但它不适用于 variable userlength。稍后我需要该列表来开发 Hangman。

任何关于代码的帮助或建议都会很棒。

def welcome():
    print("Welcome to the Hangman: ")
    userLength = input ("Please tell us how long word you want to play : ")
    print(userLength)

    text = open("test.txt").read()
    counts = Counter([len(word.strip('?!,.')) for word in text.split()])
    counts[10]
    print(counts)
    for wl in text.split():

        if len(wl) == counts :
            wordLen = len(text.split())
            print (wordLen)
            print(wl)

    filename = open("test.txt")
    lines = filename.readlines()
    filename.close()
    print (lines)
    for line in lines:
        wl = len(line)
        print (wl)

        if wl == userLength:

            words = line
            print (words)

def main ():
    welcome()

main()
4

2 回答 2

5

input函数返回一个字符串,所以你需要userLength变成一个int,像这样:

userLength = int(userLength)

事实上,这条线wl == userLength总是False.


回复:评论

这是构建具有正确长度的单词的单词列表的一种方法:

def welcome():
    print("Welcome to the Hangman: ")
    userLength = int(input("Please tell us how long word you want to play : "))

    words = []
    with open("test.txt") as lines:
        for line in lines:
            word = line.strip()
            if len(word) == userLength:
                words.append(word)
于 2013-05-13T12:18:01.057 回答
4

input()返回一个字符串 py3.x ,因此您必须先将其转换为int

userLength = int(input ("Please tell us how long word you want to play : "))

而不是使用readlines你可以一次迭代一行,它是内存高效的。其次使用with在处理文件时使用该语句,因为它会自动为您关闭文件。:

with open("test.txt") as f:
    for line in f:         #fetches  a single line each time
       line = line.strip() #remove newline or other whitespace charcters
       wl = len(line)
       print (wl)
       if wl == userLength:
         words = line
         print (words)
于 2013-05-13T12:18:19.020 回答