Advertisement
Guest User

Untitled

a guest
May 9th, 2012
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. # P2PU - Python Programming - Chapter 5 - Datatypes
  4. # Chapter 9 - Dictionaries
  5. print 'Python for Informatics - Chapter 9: Dictionaries'
  6.  
  7. # Exercise 9.1
  8. print '\n# Exercise 9.1\n'
  9. fname =  'romeo.txt'
  10. d = dict()
  11. try:
  12.     ffile = open(fname)
  13. except:
  14.     print 'File', fname, 'cannot be opened!'
  15.     exit()
  16. for line in ffile:
  17.     words = line.split()
  18.     for word in words:
  19.         if word in d:
  20.            d[word] += 1
  21.         else:
  22.            d[word] = 1
  23. print d
  24.  
  25. # Exercise 9.2
  26. print '\n# Exercise 9.2\n'
  27. def histogram(s):
  28.    d = dict()
  29.    for c in s:
  30.       d[c] = d.get(c, 0) + 1
  31.    return d
  32. print 'hippopotamus:', histogram('hippopotamus')
  33.  
  34. # Exercise 9.3
  35. print '\n# Exercise 9.3\n'
  36. fname =  'mbox-short.txt'
  37. try:
  38.     ffile = open(fname)
  39. except:
  40.     print 'File', fname, 'cannot be opened!'
  41.     exit()
  42. days = dict()
  43. for line in ffile:
  44.     words = line.split()
  45.     if len(words) < 3 or words[0] != 'From': continue
  46.     days[words[2]] = days.get(words[2], 0) + 1
  47. print days
  48.  
  49. # Exercise 9.4
  50. print '\n# Exercise 9.4\n'
  51. fname =  raw_input('Enter file name: ')
  52. try:
  53.     ffile = open(fname)
  54. except:
  55.     print 'File', fname, 'cannot be opened!'
  56.     exit()
  57. mails = dict()
  58. for line in ffile:
  59.     words = line.split()
  60.     if len(words) < 2 or words[0] != 'From': continue
  61.     mails[words[1]] = mails.get(words[1], 0) + 1
  62. mostName = None
  63. mostCount = None
  64. for mail in mails:
  65.    if mostCount == None or mostCount < mails[mail]:
  66.       mostName = mail
  67.       mostCount = mails[mail]
  68. print '%s : %d' % (mostName, mostCount)
  69.  
  70. # Exercise 9.5
  71. print '\n# Exercise 9.5\n'
  72. fname =  raw_input('Enter file name: ')
  73. try:
  74.     ffile = open(fname)
  75. except:
  76.     print 'File', fname, 'cannot be opened!'
  77.     exit()
  78. domains = dict()
  79. for line in ffile:
  80.     words = line.split()
  81.     if len(words) < 2 or words[0] != 'From': continue
  82.     domain = words[1].split('@')[1]
  83.     domains[domain] = domains.get(domain, 0) + 1
  84. print domains
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement