Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # P2PU - Python Programming - Chapter 5 - Datatypes
- # Chapter 9 - Dictionaries
- print 'Python for Informatics - Chapter 9: Dictionaries'
- # Exercise 9.1
- print '\n# Exercise 9.1\n'
- fname = 'romeo.txt'
- d = dict()
- try:
- ffile = open(fname)
- except:
- print 'File', fname, 'cannot be opened!'
- exit()
- for line in ffile:
- words = line.split()
- for word in words:
- if word in d:
- d[word] += 1
- else:
- d[word] = 1
- print d
- # Exercise 9.2
- print '\n# Exercise 9.2\n'
- def histogram(s):
- d = dict()
- for c in s:
- d[c] = d.get(c, 0) + 1
- return d
- print 'hippopotamus:', histogram('hippopotamus')
- # Exercise 9.3
- print '\n# Exercise 9.3\n'
- fname = 'mbox-short.txt'
- try:
- ffile = open(fname)
- except:
- print 'File', fname, 'cannot be opened!'
- exit()
- days = dict()
- for line in ffile:
- words = line.split()
- if len(words) < 3 or words[0] != 'From': continue
- days[words[2]] = days.get(words[2], 0) + 1
- print days
- # Exercise 9.4
- print '\n# Exercise 9.4\n'
- fname = raw_input('Enter file name: ')
- try:
- ffile = open(fname)
- except:
- print 'File', fname, 'cannot be opened!'
- exit()
- mails = dict()
- for line in ffile:
- words = line.split()
- if len(words) < 2 or words[0] != 'From': continue
- mails[words[1]] = mails.get(words[1], 0) + 1
- mostName = None
- mostCount = None
- for mail in mails:
- if mostCount == None or mostCount < mails[mail]:
- mostName = mail
- mostCount = mails[mail]
- print '%s : %d' % (mostName, mostCount)
- # Exercise 9.5
- print '\n# Exercise 9.5\n'
- fname = raw_input('Enter file name: ')
- try:
- ffile = open(fname)
- except:
- print 'File', fname, 'cannot be opened!'
- exit()
- domains = dict()
- for line in ffile:
- words = line.split()
- if len(words) < 2 or words[0] != 'From': continue
- domain = words[1].split('@')[1]
- domains[domain] = domains.get(domain, 0) + 1
- print domains
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement