Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: ipp1_2_poor_mans_bar_chart.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- - This script demonstrates "Chapter 1: Practice Project #2 - Poor Man's Bar Chart" from the book "Impractical Python Projects" by Lee Vaughan.
- - This script generates a "Poor Man’s Bar Chart" representing the frequency of each letter in a given text.
- - It maps letters from the text into a dictionary and prints the frequency of each letter along with its occurrences.
- Requirements:
- - Python 3.x
- - The following modules:
- - sys:
- Provides access to some variables used or maintained by the Python interpreter and to functions that interact strongly with the interpreter.
- - pprint:
- Provides a capability to “pretty-print” arbitrary Python data structures in a format that can be used as input to the interpreter.
- - defaultdict:
- Provides a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class.
- Usage:
- - This script can be run directly from the command line or imported as a module.
- Additional Notes:
- - Ensure that the input text provided is relatively short to ensure proper formatting of the output.
- - The script assumes the input text is in English and only considers lowercase letters for the frequency count.
- """
- import sys
- import pprint
- from collections import defaultdict
- # Note: text should be a short phrase for bars to fit in IDLE window
- text = 'Like the castle in its corner in a medieval game, I foresee terrible \
- trouble and I stay here just the same.'
- ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
- # defaultdict module lets you build dictionary keys on the fly!
- mapped = defaultdict(list)
- for character in text:
- character = character.lower()
- if character in ALPHABET:
- mapped[character].append(character)
- # Modify the list of appearances to include the count of appearances
- for letter, occurrences in mapped.items():
- count = len(occurrences)
- mapped[letter] = (count, occurrences)
- # pprint lets you print stacked output
- print("Text: \n", end='')
- print("{}\n".format(text), file=sys.stderr)
- print("Letter Frequency:")
- for letter, (count, occurrences) in mapped.items():
- frequency = f"{count}x"
- if count < 10:
- frequency = " " + frequency # Add space for single-digit frequency
- print(f"{frequency} '{letter}': {' '.join(occurrences)}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement