txt = '0 Marriage of MARY ROCHE
1 in 1880
2 Group Registration IDtN/R
3 SR District/Reg AreatCork
4 Returns Yeart1880
5 Returns Quartert4
6 Returns Volume Not5
7 Returns Page Not0110
8 Marriage of MARY ROCHE
9 in 1880
10 Group Registration IDtN/R
11 SR District/Reg AreatEnniscorthy
12 Returns Yeart1880
13 Returns Quartert3
14 Returns Volume Not4
15 Returns Page Not276"
以上是一个婚姻记录数据集的片段。每8条线对应一个新的女子纪录。我试图通过正则表达式提取关键细节(年份,区域,季度,音量,页码)。
year = re.compile(r'insd{4}')
area = re.compile(r'Areat[A-Za-z]+(?:s[A-Za-z]+)*$')
fdata = []
file = open('C:\Downloads\mary_roche.txt', 'r')
for line in file:
year_matches = year.finditer(line)
area_matches = area.finditer(line)
for a in area_matches:
for y in year_matches:
fdata.append([y.group(),a.group()])
print(len(fdata))
print(fdata)
当我单独使用这些表达式时,它们可以工作,但是当我试图将这两个表达式添加到一个列表的列表中时,我什么也得不到。我的最终目标是为所有五个关键细节创建表达式,并以有序的方式存储它们,即[[woman1], [woman2], [woman3]…]
这里的任何帮助都是非常感激的。干杯!在for
环路的逻辑中只有两个怪癖。
- 您尝试了每一行的匹配,但由于没有一条线同时包含区域和年份,因此您一无所获。补救措施:只操作数据集作为一个整体。
- 你将在所有年份迭代一个区域;这样,在第一个发现区域之后,全年的比赛都会被消耗掉。补救办法:每个区域只能获得一年的比赛。
area = re.compile(r'Areat[A-Za-z]+(?:s[A-Za-z]+)*$', re.M)
…
file = open('C:\Downloads\mary_roche.txt', 'r').read()
year_matches = year.finditer(file)
area_matches = area.finditer(file)
for a in area_matches:
y = next(year_matches)
fdata.append([y.group(), a.group()])
注意,我们需要re.MULTILINE
标志与$
,因为file
字符串现在有多行。
当然我们可以把它缩短为:
fdata = [*zip(year.findall(file), area.findall(file))]