【发布时间】:2020-10-01 16:04:28
【问题描述】:
我想打印 XML 文件中的数据。为此,我创建了一个字典来解析文件。最后,我使用了一个 for 循环在一个新的 DataFrame 中打印数据。
<BREVIER>
<BRV>
<MONO>stuff</MONO>
<TITD>stuff</TITD>
<TITF>Blabla</TITF>
<CMPD>stuff</CMPD>
<CMPF>stuff</CMPF>
<INDD>stuff</INDD>
<INDF>Blablo</INDF>
<CINDD>stuff</CINDD>
<CINDF>stuff</CINDF>
<POSD>stuff</POSD>
<POSF>stuff</POSF>
<DEL>true</DEL>
</BRV>
等等,还有很多很多 BRV 类别。
我期望的输出:
Nom_du_medicament Indication
Blabla Blablo
我试过这段代码:
# encoding: utf-8
import xmltodict
import pprint
import json
import pandas as pd
with open('Brevier.xml',encoding='UTF-8','rb') as fd:
my_dict = xmltodict.parse(fd.read(),encoding='UTF-8')
tableau_indic=pd.DataFrame()
for section in my_dict ['BREVIER']['BRV']:
drugname = section.get('TITF')
print(drugname in tableau_indic.loc(["Nom_du_medicament"]))
drugindication = section.get('INDF')
print(drugindication in tableau_indic.loc(["Indication"]))
print(tableau_indic)
fd.close()
我收到类型错误TypeError: unhashable type: 'list'
由于它不起作用,这是我尝试使用.loc的第二种方法:
# encoding: utf-8
import xmltodict
import pprint
import json
import pandas as pd
with open('Brevier.xml',encoding='UTF-8') as fd:
my_dict = xmltodict.parse(fd.read(),encoding='UTF-8')
tableau_indic=pd.DataFrame
for section in my_dict ['BREVIER']['BRV']:
drugname = section.get('TITF')
print(tableau_indic.loc["Nom_du_medicament"])
drugindication = section.get('INDF')
print(tableau_indic.loc["Indication"])
print(tableau_indic)
fd.close()
这次我遇到了KeyError: 'Nom_du_medicament' 错误。
有没有办法避免这些错误?
【问题讨论】:
-
为什么要麻烦所有这些转换而不是直接从 xml 文件打印?
-
我是初学者,这是我想象中最合乎逻辑的方式。
-
我建议您使用具有代表性的 xml 样本和该样本的预期输出来编辑您的问题,我们可以看看可以用它做什么。
-
好的,我已经添加了一个代表性的 xml 样本以及该样本的预期输出
标签: python xml pandas dataframe