python中的长度函数没有按照我想要的方式工作

AAA*_*AAA 0 python python-3.x

我是编程和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()
Run Code Online (Sandbox Code Playgroud)

Lau*_*low 5

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

userLength = int(userLength)
Run Code Online (Sandbox Code Playgroud)

事实上,这条线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)
Run Code Online (Sandbox Code Playgroud)