-
Notifications
You must be signed in to change notification settings - Fork 152
/
exercise11_1.py
executable file
·38 lines (29 loc) · 1.03 KB
/
exercise11_1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env python3
"""
Exercise 11.1: Write a simple program to simulate the operation of the grep
command on Unix. Ask the user to enter a regular expression and count the
number of lines that matched the regular expression:
$ python grep.py
Enter a regular expression: ^Author
mbox.txt had 1798 lines that matched ^Author
$ python grep.py
Enter a regular expression: ^X-
mbox.txt had 14368 lines that matched ^X-
$ python grep.py
Enter a regular expression: java$
mbox.txt had 4218 lines that matched java$
Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance
"""
import re
count = 0 # Initialize variables
input_exp = input('Enter a regular expression: ')
reg_exp = str(input_exp) # Regular Expressions are strings
fname = 'mbox.txt'
fhand = open(fname)
for line in fhand:
line = line.rstrip()
# Only counts if something was found
if re.findall(reg_exp, line) != []:
count += 1
print(fname + ' had ' + str(count) + ' lines that matched ' + reg_exp)