首页 > 解决方案 > 如何使用python根据字段值从xml部分中提取内容

问题描述

我想根据字段类型的值从 xml 文件中提取内容。基本上,它是一个 json 文件,我将其转换为 xml。该文件具有字段“body”、“id”、“type”和片段。如果'type='summary',我想提取所有这些字段的内容。我所做的代码如下:

def load_extract(data):
    path=""
    soup = BeautifulSoup(open(path),"html.parser")
    q1=[]
    qtype=[]
    snippets=[]
    for q in soup.findAll('body'):
            q=q.text
            q1.append(q)
    for types in soup.findAll('type'):

            type1=types.text
            qtype.append(type1)
    snippets=soup.findAll('snippets')
    summary_ids=[]
    summary_dict=[]
    for i in range (0, len(qtype)):
            print "extracting the summary type question"
            if qtype[i]=='summary':
               summary_ids.append(i)
    for j in summary_ids:
            summary_dict.append({q1[j]:snippets[j]})
    return summary_dict

该代码在我运行的小集合上运行良好,但对于大集合,len(q1) 不等于 len(snippets)。这就产生了一个问题。我不知道训练数据是否真的没有一些身体的片段。但这会在映射和提取方面产生问题。我在想是否可以只提取 type='summary' 的正文、id 和片段。请求您的帮助!

标签: pythonxmlbeautifulsoup

解决方案


推荐阅读