-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
20_regex_exercise.py
61 lines (46 loc) · 1.11 KB
/
20_regex_exercise.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'''
EXERCISE: Regular Expressions
'''
# open file and store each line as one list element
with open('homicides.txt', mode='rU') as f:
data = [row for row in f]
'''
Create a list of ages
'''
import re
ages = []
for row in data:
match = re.search(r'\d+ years? old', row)
if match:
ages.append(match.group())
else:
ages.append('0')
# split the string on spaces, only keep the first element, and convert to int
ages = [int(element.split()[0]) for element in ages]
# calculate average age
sum(ages) / float(len(ages))
# check that 'data' and 'ages' are the same length
assert(len(data)==len(ages))
'''
Create a list of ages (using match groups)
'''
ages = []
for row in data:
match = re.search(r'(\d+)( years? old)', row)
if match:
ages.append(int(match.group(1)))
else:
ages.append(0)
'''
Create a list of causes
'''
causes = []
for row in data:
match = re.search(r'Cause: (.+?)<', row)
if match:
causes.append(match.group(1).lower())
else:
causes.append('unknown')
# tally the causes
from collections import Counter
Counter(causes)