Advertisement
oldmagi

Chapter 11

Sep 19th, 2012
454
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. #Exercise 11.1 Write a simple program to simulate the operation of the the grep command on UNIX. Ask the user to enter a regular expression and count the number of lines that matched the regular expression:
  2. import re
  3. count=0
  4. file=open('mbox.txt')
  5. ui=input("Enter a regular expression:")
  6. for line in file:
  7.     if re.search(ui,line):
  8.         count+=1
  9. file.close()
  10. print('mbox.txt had %d lines' % count,'that matched %s' % ui)
  11.  
  12. --------------------------------------------------------------------------------------------------------------
  13. #Exercise 11.2 Write a program to look for lines of the form
  14. #New Revision: 39772
  15. #And extract the number from each of the lines using a regular expression and the findall() method. Compute the average of the numbers and print out the average.
  16. import re
  17. inp=input("Enter File:")
  18. try:
  19.     file=open(inp)
  20. except:
  21.     print("File not found")
  22.     exit()
  23.    
  24. f=[]
  25. a=0
  26. count=0
  27. for line in file:
  28.    if re.search('^New.+: \d+',line):
  29.        f=(re.findall('\d+',line))
  30.        a+=int(f[0])
  31.        count+=1
  32. file.close()
  33. print(format(a/count,'.10g'))
  34.  
  35. --------------------------------------------------------------------------------------------------------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement