我想打印XML文件中的数据。为此,我创建了一个字典来解析文件。最后,我使用for循环在新的数据帧中打印数据
<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文件,所以最好使用xpath之类的xml工具
假设您的xml如下所示:
您可以使用lxml来处理它:
输出:
从这里,您可以格式化输出,将其加载到数据帧或任何东西中
相关问题 更多 >
编程相关推荐