-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex1_extract_data
More file actions
24 lines (18 loc) · 736 Bytes
/
ex1_extract_data
File metadata and controls
24 lines (18 loc) · 736 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# This is the homework 1, which requires us to extract all the numbers from a file and add them together.
# import and read text data
import re
hand = open('regex_sum_187445.txt')
# create a numlist, an empty set, to plug in all the numbers
numlist = []
# find out all the numbers and store them in 'extract'.
# () means extract all the elements inside the parentheses. [0-9]+ means one or more digits.
for line in hand:
line = line.rstrip()
extract = re.findall("([0-9]+)", line)
# get rid of empty outcome.
if len(extract) < 1 : continue
# change the digits extracted to floating points.
for i in range(len(extract)):
num = float(extract[i])
numlist.append(num)
print(sum(numlist))