12

Python program to Count occurrences of each word in given text file

 3 years ago
source link: https://www.geeksforgeeks.org/videos/python-program-to-count-occurrences-of-each-word-in-given-text-file/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python program to Count occurrences of each word in given text file

Python program to Count occurrences of each word in given text file
Hello everyone, welcome to Geeks for
  • 30 Views
  • 20/08/2022

In this video, we'll learn how to count instances of words in a text file in Python programming.

We have used 2 approaches to do the same:
1. Using lists
2. Using Sets

Approach 1: (using lists) - In this method, we have used Python open() function to read a text file and store the data in form of string. Then we have used Python re module to extract all words from text into a list. We created a new empty dictionary.
Then we iterate on each word on the list and increment their count in the dictionary as soon as we encounter those words.

Approach 2: (using sets) - In this method, we read a text file using Python open() function and store the complete text in form of string. Then we create an empty dictionary. And next, we use Python re module's, findall() method to get a list of all the words, then this list of words is converted to a set of unique words using Python set() function. 

Then we iterate on each word on the set object and use the list.count() method to find the occurrences of the word on the list of words and store them as a key, value in the dictionary.

Python Program to Count Words in Text File
https://www.geeksforgeeks.org/python-program-to-count-words-in-text-file/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK