0

I'm trying to make a program that takes a letter the user inputs, reads a text file and then prints the words that start with that letter.

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

I keep receiving the error

"if word[0] == letter: IndexError: string index out of range"

with no lines being printed. I think this is what happens if there's nothing there, but there are 50 lines of random words in the file, so I'm not sure why it is being read this way.

1
  • Is there only one word on each line of the text file? Commented Aug 13, 2015 at 11:02

2 Answers 2

5

You have two problems:

  1. You are trying to read the whole file twice (once to determine the filelength, then again to get the lines themselves), which won't work; and
  2. You aren't dealing with empty lines, so if any are introduced (e.g. if the last line is blank) your code will break anyway.

The easiest way to do this is:

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

if line skips blanks because empty sequences are false-y, and the "lazy evaluation" of and means that line[0] will only be tried where the line isn't empty. You could alternatively use line.startswith(letter).

Sign up to request clarification or add additional context in comments.

2 Comments

It looks like the OP also wants to print the words that start with letter, as well as the count.
I'd highly second the recommendation of using line.startswith(letter) as mentioned at the end of this answer.
3

When you use sum(1 for line in f) you are already consuming all the lines in your file, so now your handle points to the end of the file. Try using f.seek(0) to return the read cursor to the start of the file.

3 Comments

Fair point, OTOH, there's no real need to count the number of lines here.
Theoretically the line count could be used in another area. I thought I'd answer the OP's question somewhat directly without inferring too much context into it, then leave the rest for OP to figure out independently. I see my job as just to get the OP programming and figuring things out on their own again, past the blocker. Not to give a general lecture on problems with the programming techniques I saw in their code sample.
That's a reasonable strategy, machine yearning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.