【发布时间】:2019-10-10 01:32:00
【问题描述】:
处理后的XML文件内容如下:
<dblp>
<incollection>
<author>Philippe Balbiani</author>
<author>Valentin Goranko</author>
<author>Ruaan Kellerman</author>
<booktitle>Handbook of Spatial Logics</booktitle>
</incollection>
<incollection>
<author>Jochen Renz</author>
<author>Bernhard Nebel</author>
<booktitle>Handbook of AI</booktitle>
</incollection>
...
</dblp>
格式内容如上图提取“author”标签内容和“booktitle”标签内容它们都在“incollection”标签中遍历每个“incollection”标签并有多个“author”标签内容带有“书名”标签的内容形式对应的元组。
我的代码:
soup = BeautifulSoup(str(getfile()), 'lxml')
res = soup.find_all('incollection')
author = []
booktitle =[]
for each in res:
for child in each.children:
if child.name == 'author':
author.append(child.text)
elif child.name == 'booktitle':
booktitle.append(child.text)
elem_dic = tuple(zip(author, booktitle))
我做的结果是:
('Philippe Balbiani', 'Handbook of Spatial Logics')
('Valentin Goranko', 'Handbook of Spatial Logics')
('Ruaan Kellerman', 'Handbook of Spatial Logics')
如何修改它以达到预期的效果?像这样:
('Philippe Balbiani', 'Handbook of Spatial Logics')
('Valentin Goranko', 'Handbook of Spatial Logics')
('Ruaan Kellerman', 'Handbook of Spatial Logics')
('Jochen Renz', 'Handbook of AI')
('Bernhard Nebel', 'Handbook of AI')
或者你可以在每个“incollection”标签中添加“booktitle”标签到与“author”标签相同的数字。
【问题讨论】:
标签: python html xml python-3.x python-2.7