Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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:
- import re
- count=0
- file=open('mbox.txt')
- ui=input("Enter a regular expression:")
- for line in file:
- if re.search(ui,line):
- count+=1
- file.close()
- print('mbox.txt had %d lines' % count,'that matched %s' % ui)
- --------------------------------------------------------------------------------------------------------------
- #Exercise 11.2 Write a program to look for lines of the form
- #New Revision: 39772
- #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.
- import re
- inp=input("Enter File:")
- try:
- file=open(inp)
- except:
- print("File not found")
- exit()
- f=[]
- a=0
- count=0
- for line in file:
- if re.search('^New.+: \d+',line):
- f=(re.findall('\d+',line))
- a+=int(f[0])
- count+=1
- file.close()
- print(format(a/count,'.10g'))
- --------------------------------------------------------------------------------------------------------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement