-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathexercise11_2.py
executable file
·45 lines (34 loc) · 960 Bytes
/
exercise11_2.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
39
40
41
42
43
44
45
#!/usr/bin/env python3
"""
Exercise 11.2: Write a program to look for lines of the form
'New Revision: 39771'
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.
Enter file:mbox.txt
38549.7949721
Enter file:mbox-short.txt
39756.9259259
Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance
"""
import re
rev = []
rev_ave = 0
fname = input('Enter file: ')
try:
fhand = open(fname)
except FileNotFoundError:
print('File cannot be opened: ', fname)
exit()
for line in fhand:
line = line.rstrip()
rev_temp = re.findall('^New Revision: ([0-9.]+)', line)
for val in rev_temp:
val = float(val) # Convert the strings to floats
rev = rev + [val] # Combine all values
rev_sum = sum(rev)
count = float(len(rev))
if count:
rev_ave = rev_sum / count
print(rev_ave)