Built with Tutify.io

    AIStudyLabs

    Word Frequency Counter

    Word Frequency Counter

    Introduction

    In this lesson, we will dive deep into the practical use of dictionaries and sets in Python to build a program that counts the frequency of words in a text. Dictionaries are potent data structures for mapping unique keys to values, making them ideal for counting occurrences. Additionally, we will explore sets to handle unique item storage, which can be beneficial in our word frequency analysis. By the end of this lesson, you will be able to read text from files, process strings, and effectively count word occurrences using Python's data manipulation capabilities.

    Dictionaries in Python

    Dictionaries are unordered collections of data in Python used to store data values in key-value pairs. Each key in a dictionary is unique and can point to a corresponding value, which is useful for efficiently storing and accessing data related by those keys.

    # Example of a dictionary
    word_count = {'Python': 1, 'programming': 2, 'lesson': 1}
    

    Sets for Unique Items

    Sets in Python are collections of unique elements. They can be utilized when you want to eliminate duplicate data and are perfect for membership tests and de-duplication tasks.

    # Example of a set
    unique_words = set(['Python', 'programming', 'lesson'])
    

    Building a Word Frequency Counter Program

    Reading Text Files

    To count word frequencies from a file, we first need to read the text content. Let's use the open() function to read a file's content.

    with open('example.txt', 'r') as file:
        text = file.read()
    

    Text Input Handling

    The text needs to be processed to ensure consistent word counting. This involves converting text to lower case and removing punctuation for accurate word matching.

    import string
    
    text = text.lower()
    text = text.translate(str.maketrans('', '', string.punctuation))
    

    Counting Word Occurrences with Dictionaries

    After processing the text, split it into words and use a dictionary to count occurrences.

    word_count = {}
    for word in text.split():
        if word in word_count:
            word_count[word] += 1
        else:
            word_count[word] = 1
    

    Example: Complete Program

    Below is the complete code for a word frequency counter:

    import string
    
    # Read and process text
    with open('example.txt', 'r') as file:
        text = file.read().lower()
        text = text.translate(str.maketrans('', '', string.punctuation))
    
    # Count word frequency
    word_count = {}
    for word in text.split():
        word_count[word] = word_count.get(word, 0) + 1
    
    # Output the result
    for word, frequency in word_count.items():
        print(f"{word}: {frequency}")
    

    Summary / Key Takeaways

    In this lesson, you have learned:

    By mastering these concepts, you are now equipped to handle textual data efficiently and can apply these skills in various programming and data analysis contexts.

    Master Python by Writing 50 Programs — Dictionary and Set Programs

    Python Basics Programs

    Number-Based Programs

    Loops and Mathematical Programs

    String-Based Programs

    List-Based Programs

    Dictionary and Set Programs

    Chapter 7: File Handling and Real Programs

    Tutorial Not Found