Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何解析按特定标记id分组的XML_Python_Xml_Dataframe - Fatal编程技术网

Python 如何解析按特定标记id分组的XML

Python 如何解析按特定标记id分组的XML,python,xml,dataframe,Python,Xml,Dataframe,我有下面的xml文件,我想用表Id对它进行分组 xml = """ <Tables Count="19"> <Table Id="1" > <Data> <Cell> <Brush/> <Text>AA</Text> <Text>BB</Text> </Cell>

我有下面的xml文件,我想用表Id对它进行分组

xml = """
 <Tables Count="19">
    <Table Id="1" >
      <Data>
        <Cell>
          <Brush/>
          <Text>AA</Text>
          <Text>BB</Text>
         </Cell>
       </Data>
    </Table>

    <Table Id="2" >
      <Data>
        <Cell>
          <Brush/>
          <Text>CC</Text>
          <Text>DD</Text>
         </Cell>
       </Data>
    </Table>
</Tables>
""" 

有可能得到上述结果吗?如果是的话,有人能帮我做这件事吗?我真的很感谢你的努力

您需要将
xpath
查询更改为:

from lxml import etree

tree = etree.fromstring(xml)

users = {}
for user in tree.xpath("//Tables/Table"):
#                                ^^^
    name = user.attrib['Id']
    users[name] = []
    for group in user.xpath(".//Data/Cell/Text"):
    #                        ^^^
        users[name].append(group.text)

print (users)
…并使用
attrib
字典。
这将为您的字符串生成:

{'1': ['AA', 'BB'], '2': ['CC', 'DD']}

如果你喜欢“一句话”,你甚至可以:

users = {name: [group.text for group in user.xpath(".//Data/Cell/Text")]
         for user in tree.xpath("//Tables/Table")
         for name in [user.attrib["Id"]]}

您需要将
xpath
查询更改为:

from lxml import etree

tree = etree.fromstring(xml)

users = {}
for user in tree.xpath("//Tables/Table"):
#                                ^^^
    name = user.attrib['Id']
    users[name] = []
    for group in user.xpath(".//Data/Cell/Text"):
    #                        ^^^
        users[name].append(group.text)

print (users)
…并使用
attrib
字典。
这将为您的字符串生成:

{'1': ['AA', 'BB'], '2': ['CC', 'DD']}

如果你喜欢“一句话”,你甚至可以:

users = {name: [group.text for group in user.xpath(".//Data/Cell/Text")]
         for user in tree.xpath("//Tables/Table")
         for name in [user.attrib["Id"]]}

你能详细说明“无法理解”吗?当我尝试执行上述代码时,我得到了以下错误:
XMLSyntaxError:Start-tag预期,'你能详细说明“无法理解”吗?当我尝试执行上述代码时,我得到了以下错误:
XMLSyntaxError:Start-tag预期,'谢谢,简,那太好了。接下来,我将尝试创建一个类似上表的数据帧。如果它不起作用,我会回来寻求你的帮助。谢谢你,简。那太好了。接下来,我将尝试创建一个类似上表的数据帧。如果它不起作用,我会回来寻求你的帮助。