Counting Words from a File
Learn how to read the number of words in a file.
We'll cover the following
Previously, we learned how to read a file and then print it onto the screen. Now, let’s take another step forward and count the number of words present in a file. Let’s look at the code widget at the end of the lesson.
Lines 3-5 should be familiar by now. First, we’ll open the file, read it, and print it.
Let’s look at an example of a new code.
Using the split()
function
Python has several inbuilt functions for strings. For instance, the split()
function splits the string on the given parameter. In the example above, we’re splitting a space. The function returns a list (which Python calls arrays) of the string split on space. To see how this works, let’s fire up an IPython console below!
Click the “Click to launch app!” button below to see how the split()
function works.
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy