forked from jmelahman/python-for-everybody-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise11_2.py
43 lines (33 loc) · 972 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
"""
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
Solution by Jamison Lahman, June 4, 2017
"""
import re
fname = input('Enter file:')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
rev = []
for line in fhand:
line = line.rstrip()
rev_temp = re.findall('^New Revision: ([0-9.]+)', line)
if rev_temp != []:
for val in rev_temp:
val = float(val) #Convert the strings to floats
rev = rev + [val] #Concats new values
rev_sum = sum(rev)
count = float(len(rev))
rev_ave = rev_sum / count
print(rev_ave)