Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''grep.py'''
- """
- 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
- pattern=raw_input("Enter a regular expression: ")
- f=open('mbox.txt')
- count=0
- for line in f:
- line=line.rstrip()
- if re.search(pattern, line):
- count+=1
- print('mbox.txt had %d that matched %s') % (count, pattern)
- exit()
- '''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
- fname = raw_input("Enter a file name: ")
- try:
- f = open(fname)
- except:
- print "The file %s doesn't exist or could not be opened." % fname
- pattern = 'New Revision: ([0-9]+)'
- l = list()
- for line in f:
- x = re.findall(pattern, line)
- if len(x) > 0:
- l.append(float(x[0]))
- print(sum(l) / len(l))
- exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement