2017-10-14 9 views
0

无法找到此特定场景的答案,如果我错过了道歉。无法比较带有用户定义的Int的Len的退货

试图定义一个函数,其中读取文本文件,将文字剥离并写入str,并显示具有用户定义范围长度的文字。

文件: “你好”, “你好”, “问候”, “HOLA”

范围:最小值:3最大值:5

输出: “你好”, “你好”, “HOLA”

当比较的话,以最小和最大输入值的len,我收到错误:

类型错误:“>”不支持的“INT”实例之间和“STR”

代码片段:

with open(filename) as f: 
    lines = f.readlines() 
    for line in lines: 
     words = line.split() 
     for word in words: 
      print(word) 
      print(len(word)) 
      if len(word) >= smallest_word and len(word) <= largest_word: 
       word_list.append(word) 

我肯定LEN返回类型为int,我是不正确的?也许我忽略了别的东西?

谢谢您的协助!

+1

在哪里最小值和最大值定义? (注意,这些已经是内置函数的名字,你应该使用不同的名字。) –

+0

好点!我会改变这些。它们在main()中用用户输入定义。 – bona221

+0

但重点是它是那些似乎是字符串,这就是为什么我要求看他们的定义。 –

回答

0

只是忘了将用户输入定义为int。对str和len的默认输入在整个时间内正确返回int。

更改:

smallest_word = input("Please enter the minimum letter amount: ") 
    largest_word = input("Please enter the maximum letter amount: ") 

要:

smallest_word = int(input("Please enter the minimum letter amount: ")) 
    largest_word = int(input("Please enter the maximum letter amount: "))