Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Exercise 9.1 Write a function that reads the words in words.txt and stores them as keys in a
- dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.
- '''
- f1=open('words.txt')
- d1=dict()
- i=0
- for line in f1:
- words=line.split()
- for i in range(len(words)):
- d1[words[i]]=i
- print d1
- print 'abc' in d1
- '''
- Exercise 9.2 Dictionaries have a method called get that takes a key and a default value. If
- the key appears in the dictionary, get returns the corresponding value; otherwise it returns the
- default value.
- Use get to write histogram more concisely. You should be able to eliminate the if statement.
- '''
- def histogram(s):
- d = dict()
- for c in s:
- d[c]=d.get(c,0)+1
- return d
- print histogram('abbcccdddd')
- '''
- Exercise 9.3 Write a program that categorizes each mail message by which day of the week
- the commit was done. To do this look for lines which start with “From”, then look for the third
- word and then keep a running count of each of the days of the week. At the end of the program
- print out the contents of your dictionary (order does not matter).
- '''
- f1=open('mail.txt')
- d1=dict()
- for line in f1:
- words=line.split()
- if words[0]=='From':
- d1[words[2]]=d1.get(words[2],0)+1
- else:
- continue
- print d1
- '''
- 9.4 Write a program to read through a mail log, and figure out who had the most
- messages in the file. The program looks for “From” lines and takes the second parameter on
- those lines as the person who sent the mail.
- The program creates a Python dictionary that maps the sender’s address to the total number of
- messages for that person.
- After all the data has been read the program looks through the dictionary using a maximum loop
- (see Section 5.7.2) to find who has the most messages and how many messages the person has.
- '''
- f1=open('mail.txt')
- d1=dict()
- for line in f1:
- words=line.split()
- if words[0]=='From':
- d1[words[1]]=d1.get(words[1],0)+1
- else:
- continue
- print d1
- '''
- Exercise 9.5 This program records the domain name (instead of the address) where the message
- was sent from instead of who the mail came from (i.e. the whole e-mail address). At the end of
- the program print out the contents of your dictionary.
- '''
- f1=open('mail.txt')
- d1=dict()
- for line in f1:
- words=line.split()
- if words[0]=='From':
- a=line.find('@')
- b=line.find(' ',a);
- c=line[a+1:b]
- d1[c]=d1.get(c,0)+1
- else:
- continue
- print d1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement