用Python解析缩进格式的文本
我在尝试找一个高效的方法来解析一些有缩进的纯文本(来自一个Word文档),结果卡住了。举个例子(注意:下面的缩进在手机版本的StackOverflow上可能看不出来):
出勤记录 8 F 1921-2010 Box 2
1921-1927, 1932-1944
1937-1939,1948-1966,
1971-1979, 1989-1994, 2010
每年参加的会议数量 1 F 1991-1994 Box 2
关于“狩猎旅行”的文件 10 F 1951-2011 Box 2
不完整;包括关于开始“狩猎旅行”的信件
可能还包括公告、邀请函、
报告、出席情况和费用;还有一些
照片。
另见:信件和会议记录
所以没有缩进的文本是父记录的数据,而每一行父数据下面的缩进文本是对该数据的一些备注(这些备注本身也分成了多行)。
到目前为止,我有一个粗糙的脚本,可以解析出没有缩进的父行,这样我就得到了一个字典项的列表:
import re
f = open('example_text.txt', 'r')
lines = f.readlines()
records = []
for line in lines:
if line[0].isalpha():
processed = re.split('\s{2,}', line)
for i in processed:
title = processed[0]
rec_id = processed[1]
years = processed[2]
location = processed[3]
records.append({
"title": title,
"id": rec_id,
"years": years,
"location": location
})
elif not line[0].isalpha():
print "These are the notes, but attaching them to the above records is not clear"
print records`
这样生成的结果是:
[{'id': '8 F',
'location': 'Box 2',
'title': '出勤记录',
'years': '1921-2010'},
{'id': '1 F',
'location': 'Box 2',
'title': '每年参加的会议数量',
'years': '1991-1994'},
{'id': '10 F',
'location': 'Box 2',
'title': '关于“狩猎旅行”的文件',
'years': '1951-2011'}]
但现在我想给每条记录添加备注,像这样:
[{'id': '8 F',
'location': 'Box 2',
'title': '出勤记录',
'years': '1921-2010',
'notes': '1921-1927, 1932-1944 1937-1939,1948-1966, 1971-1979, 1989-1994, 2010'
},
...]
让我困惑的是,我假设这种逐行处理的方法,但我不确定是否有更“Pythonic”的方式来做到这一点。我更习惯于处理网页抓取,至少在那种情况下你有选择器,而这里很难逐行回头去处理。我希望有人能帮我理清思路,提供一个更好的解决方案。
更新 我只是添加了下面回答中建议的条件,处理缩进行时效果很好:
import re
import repr as _repr
from pprint import pprint
f = open('example_text.txt', 'r')
lines = f.readlines()
records = []
for line in lines:
if line[0].isalpha():
processed = re.split('\s{2,}', line)
#print processed
for i in processed:
title = processed[0]
rec_id = processed[1]
years = processed[2]
location = processed[3]
if not line[0].isalpha():
record['notes'].append(line)
continue
record = { "title": title,
"id": rec_id,
"years": years,
"location": location,
"notes": []}
records.append(record)
pprint(records)
1 个回答
既然你已经解决了记录的解析问题,我就只讲讲怎么读取每条记录的备注:
records = []
with open('data.txt', 'r') as lines:
for line in lines:
if line.startswith ('\t'):
record ['notes'].append (line [1:])
continue
record = {'title': line, 'notes': [] }
records.append (record)
for record in records:
print ('Record is', record ['title'] )
print ('Notes are', record ['notes'] )
print ()