首页 > 解决方案 > 从格式不正确的 XML 中获取列名

问题描述

我有一个格式不正确的 XML,因为我在尝试读取 XML 时收到此错误:

import xml.etree.ElementTree as ET
ET.parse(r'my.xml')

我收到以下错误

ParseError:格式不正确(无效标记):第 2034 行,第 317 列

因此,我曾经BeautifulSoup通过以下代码读取 xml:

from bs4 import BeautifulSoup

with open(r'my.xml') as fp:
    soup = BeautifulSoup(fp, 'xml')

如果我打印soup它看起来像这样:

        <Placemark> 
<name>India </name> 
    <description>Country</description> 
    <styleUrl>#icon-962-B29189</styleUrl> 
    </Placemark>
        <Placemark> 
<name>USA</name>   
    <styleUrl>#icon-962-B29189</styleUrl> 
    </Placemark>            
    <Placemark>   
    <description>City</description> 
    <styleUrl>#icon-962-B29189</styleUrl> 
    </Placemark>

我总共有 100 多个Placemark标签和其中的信息。我想捕获每个标签的 and 并用各自的列制作name一个。descriptiondf

我的代码是:

name_tag=[x.text.strip() for x in soup.findAll('name')]
description_tag =[x.text.strip() for x in soup.findAll('description')]

问题在于Placemark我没有name或根本没有标签的一些description标签。因此我不知道哪个名字有什么描述。因此,由于缺少标签,名称和描述之间存在不匹配。

预期输出数据框

Name      Description
India     Country
USA
           City

他们有什么方法可以达到同样的效果吗?

标签: pythonpandasbeautifulsoupxml-parsing

解决方案


由于您正在分别搜索namedescription标记,因此您无法跟踪哪个名称属于哪个描述。

相反,您应该placemark自己解析每个标签,并处理每个地标标签的缺失namedescription标签的情况。

data = []

for placemark in soup.findAll('placemark'):
    try:
        name = placemark.find('name').text.strip()
    except AttributeError:
        name = None
    try:
        description = placemark.find('description').text.strip()
    except AttributeError:
        description = None

    data.append((name, description))

df = pd.DataFrame(data, columns=['Name', 'Description'])
print(df)
#       Name    Description
#  0   India        Country
#  1     USA           None
#  2    None           City

推荐阅读