Python Reading Words From a Web Page
Reading words from a web page means splitting fetched text into single words. The split words can then be counted and compared.
Split the fetched text
split() cuts the fetched text at the spaces. The result is a list of words.
from urllib.request import urlopen
reply = urlopen('data:text/plain,The%20cat%20sat%20on%20the%20mat%20The%20cat%20slept')
words = reply.read().decode().split()
print(words)Count the words
len() counts the words in the list. The page holds nine words.
from urllib.request import urlopen
reply = urlopen('data:text/plain,The%20cat%20sat%20on%20the%20mat%20The%20cat%20slept')
words = reply.read().decode().split()
print(len(words))Find the longest word
max() with key=len picks the word with the most letters. The longest word is slept.
from urllib.request import urlopen
reply = urlopen('data:text/plain,The%20cat%20sat%20on%20the%20mat%20The%20cat%20slept')
words = reply.read().decode().split()
print(max(words, key=len))Count one word
A dict keeps a count for each word. The word cat appears twice.
from urllib.request import urlopen
reply = urlopen('data:text/plain,The%20cat%20sat%20on%20the%20mat%20The%20cat%20slept')
words = reply.read().decode().split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts["cat"])Example
from urllib.request import urlopen
reply = urlopen('data:text/plain,The%20cat%20sat%20on%20the%20mat%20The%20cat%20slept')
words = reply.read().decode().split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print("Words:", len(words))
print("Longest:", max(words, key=len))
print("Cat count:", counts["cat"])
print("Counts:", counts)Key points
- split(): a method that cuts text into a list of words
- Use text.split() to split text at the spaces
- Use len(words) to count the words
- Use max(words, key=len) to find the longest word
- Use a dict to count how often one word appears
- Use counts.get(word, 0) to start a new word at zero
- The longest word is the word with the most letters
In this example, urlopen() fetches nine words from a data address. read() brings the words back as bytes. decode() turns the bytes into plain text. split() cuts the text into a list of words. The loop counts each word in a dict. The printouts show the word count, the longest word, the count for cat, and the full counts. The numbers prove the split and the count worked.
Note
Cat and cat count as two different words, because split() keeps the capitals as they are.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does text.split() give back?