Dhomaseghanshyam.files.wordpress.com
Python Assignment-1
Program to Count the Occurrences of a Word in a Text File
This is a Python Program to count the occurrences of a word in a text file.
Problem Description
The program takes a word from the user and counts the number of occurrences of that word in a file.
Problem Solution
1. Take the file name and the word to be counted from the user.
2. Read each line from the file and split the line to form a list of words.
3. Check if the word provided by the user and any of the words in the list are equal and if they are, increment the word count.
4. Exit.
Program/Source Code
Here is source code of the Python Program to count the occurrences of a word in a text file. The program output is also shown below.
fname = input("Enter file name: ")
num_words = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
print("Number of words:")
print(num_words)
Program Explanation
1. User must enter a file name and the word to be searched.
2. The file is opened using the open() function in the read mode.
3. A for loop is used to read through each line in the file.
4. Each line is split into a list of words using split().
5. Another for loop is used to traverse through the list and each word in the list is compared with the word provided by the user.
6. If both the words are equal, the word count is incremented.
7. The final count of occurrences of the word is printed.
Output
Create one a.txt file
[pic]
Enter file name: a.txt
Number of words:
2
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- counting occurrences for a finite set of words an
- text analysis with nltk cheatsheet
- practical file class xii computer science with
- lab manual python programming lab 6cs4 23 jnit
- introduction to python borenstein lab
- programming for engineers in python
- python count number of occurrences of a substring in string
- indexing and slicing
- list example counting occurrences of letters
- prof dipesh agrawal
Related searches
- wordpress passing data between pages
- wordpress business templates
- wordpress rss feed not working
- wordpress jquery is not defined
- create wordpress blog
- wordpress roles editor
- wordpress full rss feed
- wordpress rss feed settings
- wordpress rss feed plugin
- wordpress display rss feed
- wordpress rss feed link
- wordpress rss feed to post