AMS 209: HW 5: Problem 2ΒΆ

 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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#!/usr/bin/env python3
# coding: utf8

'''
Created on November 6th, 2017

@author: Geetanjali
'''


def file2string(filename):
	"""
	:param filename: name of file from which words are read
	:return fstring: all the contents of the file are read into a string fstring and returned
	"""

	fstring=open(filename).read()
	return fstring

def histogram(string):
	"""
	:param string: a string from which we find frequency of each character
	:return d: a dictionary containing all the characters in string as keys and their frequencies as values
	"""
	
	d = {}
    
	for c in string:
		if c not in d:
			# if c first appears as a key in d
			# then initialize its value to one.
			d[c] = 1
		else:
			# if c appears as a key more than once
			# add its value by one.
			d[c] += 1
	return d

def getCharacterCounts(filename):
	"""
	:param filename: name of file from which words are read
	:return histogram(fstring): a dictionary containing all the characters in the file as keys and their frequencies as values
	"""

	fstring = file2string(filename)
	return(histogram(fstring))

def print_hist(d):
	"""
	:param d: a dictionary with characters as keys and their frequencies as values
	:return : doesn't return anything. Prints the key,value pairs in d as tuples, one in each line
	"""

	d_tuple = ()
	for key, value in d.items():
		d_tuple = (key, value)
		print(d_tuple)

if __name__ == '__main__':

	filename = "words.txt"
	d = getCharacterCounts(filename)
	print_hist(d)