-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathletterfrequency.py
More file actions
executable file
·32 lines (23 loc) · 952 Bytes
/
letterfrequency.py
File metadata and controls
executable file
·32 lines (23 loc) · 952 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/usr/local/bin/python3
# Example Python program to determine the letter/character frequency in text
import sys
if sys.version_info[0] < 3:
raise Exception("Must be using python 3")
# initialize the dictionary holding the results of the letter frequencies
freq_dict = {}
for i in list("abcdefghijklmnopqrstuvwxyz") : freq_dict[i] = 0 # initial count of 0 for each letter in list
# sample text
text = "Mary had a little lamb whose fleece was white as snow and everywhere that mary went the lamb was sure to go."
# normalize the text to lower case
text_lower = text.lower()
# replace (r) all non-word characters (\W) with an empty string ('')
import re
text_cleaned = re.sub(r'\W+', '', text_lower)
# compute frequency
for i in list(text_cleaned):
freq_dict[i] += 1
# summarize results
print ("Input Text: "+text)
for (key, value) in freq_dict.items():
print("Letter "+key+" appears "+str(value)+" times")
print ("Done")