1

I am learning Python and currently I have a text file. Within that text file, I want to search for the words I already have within a list ['mice', parrot'] and get a count of how many times mice and parrot have been mentioned. I currently have.

enter code herewith open('animalpoem.txt', 'r') as animalpoemfile:
data = animalpoemfile.read()
search animals = ['mice', parrot']                               
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • You might find an answer here: https://stackoverflow.com/questions/4783899/counting-lines-words-and-characters-within-a-text-file-using-python?rq=1 – Cireo Jun 22 '20 at 18:29
  • 3
    Does this answer your question? [How can I count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item) – sdcbr Jun 22 '20 at 18:31

4 Answers4

1

To count the number of occurrences of a specific word in a text file, read the content of text file to a string and use String.count() function with the word passed as argument to the count() function.

Syntax:

n = String.count(word)

where word is the string, and count() returns the number of occurrences of word in this String.

So you can read the file and make use of count() method.

#get file object reference to the file
with open("file.txt", "r") as file:
    #read content of file to string
    data = file.read()

words = ['apple', 'orange']

for word in words:
    print('{} occurred {} times.'.format(word, data.count(word)))

Hopefully, this should work fine.

Note: You can even loop through each and every word and increment the counter. But using a high-level programming language like Python, it would be beneficial to make use of such built-in methods.

Michael Green
  • 719
  • 6
  • 15
Nitin1901
  • 140
  • 1
  • 10
0

An example solution:

import re

animals = ['mice', 'parrot']

# make a dictionary with keys being the names of the animals,
# and values being initial counts (0)
counts = dict([(a, 0) for a in animals])

with open("animalpoem.txt") as f:
     for line in f:  # loop over lines of the file, assign to variable "line"
          for word in re.findall("\w+", line.lower()):  # convert to lower case and make list of words and then iterate over it
               if word in counts:  # tests if the word is one of the keys in the dictionary
                    counts[word] += 1  # if so, increments the count value associated with that word

print(counts)

animalpoem.txt

Three blind mice. Three blind mice.
See how they run. See how they run.
They all ran after the farmer's wife,
Who cut off their tails with a carving knife,
Did you ever see such a sight in your life,
As three blind mice?

Program output:

{'mice': 3, 'parrot': 0}
alani
  • 12,573
  • 2
  • 13
  • 23
0

steps

  1. open file
  2. read file and store in a variable
  3. count the word you want to search for in this variable
    def num_of_word_in_file(file_name, word):
      with open(file_name) as file:
        content = file.read()
      return content.count(word)
    for animal in animals :
        print(num_of_word_in_file(file_name, animal))
    
0

You can use the Counter() method from the collections module:

from collections import Counter

with open('t.txt', 'r') as animalpoemfile:
    dct = Counter(animalpoemfile.read().split())

search_animals = ['mice', 'parrot']
    
for animal in search_animals:
    print(animal, dct[animal])
Red
  • 26,798
  • 7
  • 36
  • 58