Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

For this problem, you will write a program to form a frequency table of the letters in a text file, that is, how many times

For this problem, you will write a program to form a frequency table of the letters in a text file, that is, how many times each letter appears in the file In Python 3.7.

Such a frequency table might be useful for compressing a text file. Because different letters appear with different frequencies, we can compress a file by using shorter codes for common letters and longer codes for letters that appear less frequently.

Dictionaries provide an elegant way to generate a frequency table:

>>> letter_counts = {}

>>> for letter in "Mississippi":

... letter_counts[letter] = letter_counts.get(letter, 0) + 1

...

>>> letter_counts

{'M': 1, 's': 4, 'p': 2, 'i': 4}

We start with an empty dictionary. For each letter in the string, we find the current count (possibly zero) and increment it. At the end, the dictionary contains pairs of letters and their frequencies.

It might be more appealing to display the frequency table in alphabetical order. We can do that with the items and sort methods:

>>> letter_items = list(letter_counts.items())

>>> letter_items.sort()

>>> print(letter_items)

[('M', 1), ('i', 4), ('p', 2), ('s', 4)]

Notice in the first line we had to call the type conversion function list. That turns the promise we get from items into a list, a step that is needed before we can use the lists sort method.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Beginning C# 2005 Databases

Authors: Karli Watson

1st Edition

0470044063, 978-0470044063

More Books

Students also viewed these Databases questions

Question

=+8. Why is productivity important?

Answered: 1 week ago

Question

=+ 9. What is inflation and what causes it?

Answered: 1 week ago

Question

=+6. What does the invisible hand of the marketplace do?

Answered: 1 week ago