python中的length函数不能按照我想要的方式工作

时间:2013-05-13 12:14:37

标签: python python-3.x

我是编程和python的新手。我在网上寻求帮助,我正如他们所说,但我认为我犯的是一个我无法捕捉到的错误。 现在我要做的就是:如果单词与用户输入的长度与文件中的单词匹配,请列出这些单词。如果我用实际数字替换userLength但它不能使用变量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()

2 个答案:

答案 0 :(得分:4)

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)

答案 1 :(得分:3)

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)