python - 从格式不正确的 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
一个。description
df
我的代码是:
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
他们有什么方法可以达到同样的效果吗?
解决方案
由于您正在分别搜索name
和description
标记,因此您无法跟踪哪个名称属于哪个描述。
相反,您应该placemark
自己解析每个标签,并处理每个地标标签的缺失name
和description
标签的情况。
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
推荐阅读
- swift - 如何根据iOS版本在一个应用程序中添加两个应用程序?
- r - 在 R Jags 中模拟 Pareto 分布(贝叶斯)
- javascript - 检查 JavaScript 对象中的多个键?
- angular - 无法在angular7中查看html中的数据
- entity-framework - Automapper:映射多对多
- erlang - 为 file:get_cwd() 获取 {error, enoent} 的常见原因是什么?
- python-3.x - 在列中出现两行
- angular - 默认情况下选中单选按钮,它们不应该被选中
- android - 我想找到用户的行程详细信息(行程起点、终点、速度、硬中断、电话使用情况、事故)。(安卓开发)
- django - 带有mongoengine的django rest框架中不区分大小写的排序