The following sequence of steps illustrates you how to count number of words in a text file.
To count the number of words in a text file, follow these steps.
- Open the file in read mode and handle it in text mode.
- Read the text using read() function.
- Split the text using space separator. We assume that words in a sentence are separated by a space character.
- The length of the split list should equal the number of words in the text file.
- You can refine the count by cleaning the string prior to splitting or validating the words after splitting.
To do this first you need to upload a text into your "Jupyter Note book" by clicking on "Upload" button. After you will get a blue color upload button again click on it finish the process. The text file should contain the following lines and save the file name as "data" ( Use notepad to create text file)
"Welcome to tutorialtpoint.net. Here, you will find python programs for all general use cases"
The following program will count number of word in data text file
file = open("data.txt", "rt") data = file.read() words = data.split() print(" Number of words in text file", len(words));
The following is the output
Number of words in text file : 14
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.