Advertisement
Guest User

P2PU Python course: exercises chapter 11

a guest
Apr 7th, 2013
845
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. '''grep.py'''
  2. """
  3. Exercise 11.1 Write a simple program to simulate the operation of the the
  4. grep command on UNIX. Ask the user to enter a regular expression and count
  5. the number of lines that matched the regular expression
  6. """
  7. import re
  8. pattern=raw_input("Enter a regular expression: ")
  9. f=open('mbox.txt')
  10. count=0
  11. for line in f:
  12.     line=line.rstrip()
  13.     if re.search(pattern, line):
  14.         count+=1
  15. print('mbox.txt had %d that matched %s') % (count, pattern)
  16. exit()
  17.  
  18.  
  19. '''Exercise 11.2'''
  20. '''Write a program to look for lines of the form '''
  21. '''New Revision: 39772'''
  22. '''And extract the number from each of the lines using a regular expression'''
  23. ''' and the findall() method. Compute the average of the numbers '''
  24. '''and print out the average.'''
  25. import re
  26. fname = raw_input("Enter a file name: ")
  27. try:
  28.     f = open(fname)
  29. except:
  30.     print "The file %s doesn't exist or could not be opened." % fname
  31. pattern = 'New Revision: ([0-9]+)'
  32. l = list()
  33. for line in f:
  34.     x = re.findall(pattern, line)
  35.     if len(x) > 0:
  36.         l.append(float(x[0]))
  37. print(sum(l) / len(l))
  38. exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement