如何将XML文件转换为漂亮的熊猫数据框?

假设我有一个像这样的XML:

<author type="XXX" language="EN" gender="xx" feature="xx" web="foobar.com">
    <documents count="N">
        <document KEY="e95a9a6c790ecb95e46cf15bee517651" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>        </document>
        <document KEY="bc360cfbafc39970587547215162f0db" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>        </document>
        <document KEY="19e71144c50a8b9160b3f0955e906fce" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>        </document>
        <document KEY="21d4af9021a174f61b884606c74d9e42" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>        </document>
        <document KEY="28a45eb2460899763d709ca00ddbb665" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>        </document>
        <document KEY="a0c0712a6a351f85d9f5757e9fff8946" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>        </document>
        <document KEY="626726ba8d34d15d02b6d043c55fe691" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>        </document>
        <document KEY="2cb473e0f102e2e4a40aa3006e412ae4" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...] [...]
]]>        </document>
    </documents></author>

有人可以为我解决这个问题提供更好的方法吗?



慕工程0101907
浏览 487回答 3
3回答

缥缈止盈

您还可以通过创建元素字典来进行转换,然后直接转换为数据框:import&nbsp;xml.etree.ElementTree&nbsp;as&nbsp;ETimport&nbsp;pandas&nbsp;as&nbsp;pd#&nbsp;Contents&nbsp;of&nbsp;test.xml#&nbsp;<?xml&nbsp;version="1.0"&nbsp;encoding="utf-8"?>&nbsp;<tags>&nbsp;&nbsp;&nbsp;<row&nbsp;Id="1"&nbsp;TagName="bayesian"&nbsp;Count="4699"&nbsp;ExcerptPostId="20258"&nbsp;WikiPostId="20257"&nbsp;/>&nbsp;&nbsp;&nbsp;<row&nbsp;Id="2"&nbsp;TagName="prior"&nbsp;Count="598"&nbsp;ExcerptPostId="62158"&nbsp;WikiPostId="62157"&nbsp;/>&nbsp;&nbsp;&nbsp;<row&nbsp;Id="3"&nbsp;TagName="elicitation"&nbsp;Count="10"&nbsp;/>&nbsp;&nbsp;&nbsp;<row&nbsp;Id="5"&nbsp;TagName="open-source"&nbsp;Count="16"&nbsp;/>&nbsp;</tags>root&nbsp;=&nbsp;ET.parse('test.xml').getroot()tags&nbsp;=&nbsp;{"tags":[]}for&nbsp;elem&nbsp;in&nbsp;root: &nbsp;&nbsp;&nbsp;&nbsp;tag&nbsp;=&nbsp;{} &nbsp;&nbsp;&nbsp;&nbsp;tag["Id"]&nbsp;=&nbsp;elem.attrib['Id'] &nbsp;&nbsp;&nbsp;&nbsp;tag["TagName"]&nbsp;=&nbsp;elem.attrib['TagName'] &nbsp;&nbsp;&nbsp;&nbsp;tag["Count"]&nbsp;=&nbsp;elem.attrib['Count'] &nbsp;&nbsp;&nbsp;&nbsp;tags["tags"].&nbsp;append(tag)df_users&nbsp;=&nbsp;pd.DataFrame(tags["tags"])df_users.head()
打开App,查看更多内容
随时随地看视频慕课网APP