IndexError:字符串索引超出范围,行是空的?

0 python

我正在尝试创建一个程序,它接受用户输入的字母,读取文本文件,然后打印以该字母开头的单词.

item = "file_name"
letter = raw_input("Words starting with: ")
letter = letter.lower()
found = 0

with open(item) as f:
    filelength = sum(1 for line in f)
    for i in range (filelength):
        word = f.readline()
        print word
        if word[0] == letter:
            print word
            found += 1
    print "words found:", found
Run Code Online (Sandbox Code Playgroud)

我一直收到错误

"如果word [0] == letter:IndexError:字符串索引超出范围"

没有印刷线.我认为如果没有任何内容会发生这种情况,但文件中有50行随机单词,所以我不确定为什么会这样读.

jon*_*rpe 5

你有两个问题:

  1. 您试图读取整个文件两次(一次确定filelength,然后再次获取行本身),这将无效; 和
  2. 你没有处理空行,所以如果引入了空行(例如,如果最后一行是空白的话),你的代码无论如何都会破坏.

最简单的方法是:

found = 0

with open(item) as f:
    for line in f:  # iterate over lines directly
        if line and line[0] == letter:  # skip blank lines and any that don't match
                found += 1
print "words found:", found
Run Code Online (Sandbox Code Playgroud)

if line跳过坯料因为空序列为假-γ,和"懒评价"and该装置line[0]将仅试图其中线是不空的.你也可以使用line.startswith(letter).