2013-05-13 52 views
0

我是编程和python的新手。我在网上寻找帮助,我按照他们的说法行事,但我认为我犯了一个我无法理解的错误。 现在我所要做的就是:如果单词与用户在文件中输入单词的长度相匹配,请列出这些单词。如果我用实际的号码替换userLength,但它不适用于变量userlength。我以后需要这个名单来开发Hang子手。python中的长度函数不能按我想要的方式工作

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

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() 

回答

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) 
+0

明白了。谢谢。 – AAA 2013-05-13 12:21:04

4

input函数返回一个字符串,所以你需要把userLengthint,像这样:

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) 
+0

有道理。我正在打印它正在打印长度的用户长度,所以我不确定。你能告诉我如何创建一个列表。 'Words'应该是一个列表,但它一次只给我一个单词。 感谢您的帮助。 – AAA 2013-05-13 12:20:40

+0

@AAA您已经有了变量'lines'中的单词列表,尽管每个单词都以换行结束。要删除它们,请执行'lines = [word.string()')。 – 2013-05-13 12:29:41

+0

由于这是推荐阿什维尼,我改变了代码的那部分 张开( “test.txt的”)为f: #lines = filename.readlines() #filename.close() #PRINT(线) 线路f中: 线= [word.strip(),用于线的字] WL = LEN(线) 打印(WL) 如果WL == userLength: 词语=行 打印(字) – AAA 2013-05-13 12:40:34

相关问题