From the course: Python: Working with Files
Unlock this course with a free trial
Join today to access over 25,400 courses taught by industry experts.
Solution: Find most common word in files - Python Tutorial
From the course: Python: Working with Files
Solution: Find most common word in files
- [Instructor] Let's find the most common word in a set of files using Python. In the sample code, we're given two helper methods, create_directory and create_file. These are used in the test code, so we can change how many files we use and what they contain. To keep track of the word counts for each word we find, we'll use a dictionary. Then we'll create a path for the directory and iterate through all of its files using iterdir. (keyboard clacking) From pathlib, we'll import path. This will allow us to use this functionality. (keyboard clacking) For each file, we'll open it up in read mode. Then we'll read its text into memory. Once we have the text, we'll split it into words. (keyboard clacking) For each word, we'll convert it to lowercase and then add it to our dictionary. This is how we'll keep track of the most common word. (keyboard clacking) If the word is already in our dictionary, we'll retrieve its frequency and add 1 to it. If it does not exist, we'll make its current…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.