Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # P2PU - Python Programming - Chapter 5 - Datatypes
- # Chapter 10 - Tuples
- print 'Python for Informatics - Chapter 10: Tuples'
- # Exercise 10.1
- print '\n# Exercise 10.1\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
- lst = list()
- for key, val in mails.items():
- lst.append((val,key))
- lst.sort(reverse=True)
- print lst[0][1], ':', lst[0][0]
- # Exercise 10.2
- print '\n# Exercise 10.2\n'
- fname = raw_input('Enter file name: ')
- try:
- ffile = open(fname)
- except:
- print 'File', fname, 'cannot be opened!'
- exit()
- hcount = dict()
- for line in ffile:
- words = line.split()
- if len(words) < 6 or words[0] != 'From': continue
- h = words[5].split(':')
- hcount[h[0]] = hcount.get(h[0], 0) + 1
- lst = list()
- for key, val in hcount.items():
- lst.append((key,val))
- lst.sort()
- for key, val in lst:
- print key, val
- # Exercise 10.3
- import string
- print '\n# Exercise 10.3\n'
- def most_frequent(f):
- #small change: function takes a file instead of a string
- letters = dict()
- for line in ffile:
- # remove puntuation
- line = line.translate(None, string.punctuation)
- # remove spaces
- line = line.translate(None, ' ')
- # all lowercase
- line = line.lower()
- # remove numbers
- line = line.translate(None, '0123456789')
- # remove newlines
- line = line.strip()
- for letter in line:
- letters[letter] = letters.get(letter, 0) + 1
- lst = list()
- for key, val in letters.items():
- lst.append((val,key))
- lst.sort(reverse=True)
- return lst
- fname = raw_input('Enter file name: ')
- try:
- ffile = open(fname)
- except:
- print 'File', fname, 'cannot be opened!'
- exit()
- res = most_frequent(ffile)
- for key, val in res[0:10]:
- print key, val
- # Top 10 letters from newspaper article in
- # English: e t a n s o i r h l
- # French: e s a n i t l r u o
- # Dutch: e n t a i r d l o s
- # German: e n a r i s t h u l
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement