baeb
baeb

Reputation: 11

How to read a text file in Python

I have an assignment that reads:

Write a function which takes the input file name and list of words and write into the file “Repeated_word.txt” the word and number of times word repeated in input file?

word_list = [‘Emma’, ‘Woodhouse’, ‘father’, ‘Taylor’, ‘Miss’, ‘been’, ‘she’, ‘her’]

My code is below.

All it does is create the new file 'Repeated_word.txt' however it doesn't write the number of times the word from the wordlist appears in the file.


#obtain the name of the file
filename = raw_input("What is the file being used?: ")
fin = open(filename, "r")


#create list of words to see if repeated
word_list = ["Emma", "Woodhouse", "father", "Taylor", "Miss", "been", "she", "her"]

def repeatedWords(fin, word_list):
    #open the file
    fin = open(filename, "r")
    #create output file
    fout = open("Repeated_word.txt", "w")
    #loop through each word of the file
    for line in fin:
        #split the lines into words
        words = line.split()
        for word in words:
            #check if word in words is equal to a word from word_list
            for i in range(len(word_list)):
                if word == i:
                    #count number of times word is in word
                    count = words.count(word)
                    fout.write(word, count)
    fout.close

repeatedWords(fin, word_list)

Upvotes: 0

Views: 1436

Answers (2)

El'endia Starman
El'endia Starman

Reputation: 2244

These lines,

        for i in range(len(word_list)):
            if word == i:

should be

        for i in range(len(word_list)):
            if word == word_list[i]:

or

        for i in word_list:
            if word == i:

word is a string, whereas i is an integer, the way you have it right now. These are never equal, hence nothing ever gets written to the file.


In response to your further question, you can either 1) use a dictionary to keep track of how many of each word you have, or 2) read in the whole file at once. This is one way you might do that:

words = fin.read().split()
for word in word_list:
    fout.write(word, words.count(word), '\n')

I leave it up to you to figure out where to put this in your code and what you need to replace. This is, after all, your assignment, not ours.

Upvotes: 1

Mehrdad
Mehrdad

Reputation: 1256

Seems like you are making several mistakes here:

  [1]  for i in range(len(word_list)):
  [2]      if word == i:
  [3]          #count number of times word is in word
  [4]          count = words.count(word)
  [5]          fout.write(word, count)

First, you are comparing the word from cin with an integer from the range. [line 2]

Then you are writing the count to fout upon every match per line. [line 5] I guess you should keep the counts (e.g. in a dict) and write them all at the end of parsing input file.

Upvotes: 0

Related Questions