-
Notifications
You must be signed in to change notification settings - Fork 377
/
99_regex_example.py
77 lines (58 loc) · 1.32 KB
/
99_regex_example.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'''
CLASS: Regular Expressions Example
'''
'''
Open file
'''
# open file and store each line as one row
with open('../data/homicides.txt', 'rU') as f:
raw = [row for row in f]
'''
Create a list of ages
'''
import re
ages = []
for row in raw:
match = re.search(r'\d+ years old', row)
if match:
ages.append(match.group())
else:
ages.append('0')
ages = [int(element.split()[0]) for element in ages]
# simplify process using a lookahead
ages = []
for row in raw:
match = re.search(r'\d+(?= years)', row)
if match:
ages.append(int(match.group()))
else:
ages.append(0)
'''
Create a list of causes
'''
causes = []
for row in raw:
match = re.search(r'Cause: .+?<', row)
if match:
causes.append(match.group())
else:
causes.append('Cause: unknown<')
causes = [element[7:-1] for element in causes]
# simplify process using a lookahead and a lookbehind
causes = []
for row in raw:
match = re.search(r'(?<=Cause: ).+?(?=<)', row)
if match:
causes.append(match.group())
else:
causes.append('unknown')
'''
Generate simple statistics
'''
from collections import Counter
c_ages = Counter(ages)
sum(c_ages.values()) # 1250
c_ages[0] # 22
c_causes = Counter(causes)
sum(c_causes.values()) # 1250
c_causes.most_common()