【问题标题】:Memory full and other problems parsing large size xml file解析大尺寸 xml 文件时内存已满等问题
【发布时间】:2021-09-05 08:13:34
【问题描述】:

我有一个 XML 跟踪文件,该文件的大小约为 350 Mb。当我一次使用以下代码时,它会产生内存已满问题,而另一次会产生关于无法解析文件的错误。解析这么大的文件应该怎么做?是否使用不同的方法进行解析?

    root = ET.parse('E:/software/jm_16.1/bin/tracefile.xml').getroot()
    lst = root.findall('AVCTrace/Picture/SubPicture/Slice/MacroBlock')
    for item in lst:
        print (item.get('QP_Y'))

I also produce a smaller file and based on the above file and the variable `lst` is empty!!. do you know what is the problem?
my XML trace file is as follows:

    I also need to extract X tag and Y tag in Macroblock. for this I used <MacroBlock num="8158">
                <SubMacroBlock num="0">
                    <Type>1</Type>
                    <TypeString>B_L0_8x8</TypeString>
                    <MotionVector list="0">
                        <RefIdx>0</RefIdx>
                        <Difference>
                            <X>-1</X>
                            <Y>-2</Y>
                        </Difference>
                        <Absolute>
                            <X>-4</X>
                            <Y>-6</Y>
                        </Absolute>
                    </MotionVector>
                </SubMacroBlock>

【问题讨论】:

  • 使用lxml
  • 谢谢。使用 ET 我可以解析它,但是当我使用 item.get('QP_Y') 时它什么也得不到,而且它们都是无。如何实现 QP_Y 的值?例如在上面的例子中是 28。
  • lst 是一个包含 979200 个元素的列表。
  • @JonSG 你的评论是关于我最后一个关于寻找 QP_Y 值的问题?

标签: python python-3.x xml-parsing


【解决方案1】:
import xml.etree.ElementTree as ET


root = ET.parse('68071609.xml').getroot()
print(root.tag)  # Picture
elems = root.findall('SubPicture/Slice/MacroBlock/QP_Y')
for elem in elems:
    print(elem.text)  # 28

你的树的根已经是Picture,所以你不应该在里面搜索Picture/...
您可以通过将其添加到搜索路径来直接搜索所有名为QP_Y 的节点。

如果您更喜欢迭代宏块,并拥有它们的 QP_Y :

elems = root.findall('SubPicture/Slice/MacroBlock')
for elem in elems:
    print(elem.attrib)  # {'num': '0'}
    qp_y = next(child for child in elem if child.tag == "QP_Y").text  # will throw StopIteration if missing
    print(qp_y)  # 28

【讨论】:

  • 这是一种将所有 QP_Y 值放入数组而不使用 for 循环访问每个项目的方法吗?
  • list(qpy_node.text for qpy_node in root.findall('SubPicture/Slice/MacroBlock/QP_Y'))
  • 我在上面使用了你的新评论,但是当我想在宏块中实现 TypeString 时,它只返回一个元素,而我有大约 902000 个元素 tsMB=list(qpy_node.text for qpy_node in root.findall('图片/子图片/切片/宏块/TypeString'))
  • @david:您已经接受了答案。如果您还有其他问题,请提出一个新问题。在发布此答案后,您还对问题进行了大量编辑。不要那样做。
  • 我在这里提出的问题是关于发布的答案,我接受了这一点,所以当某些示例不起作用时,这意味着它有问题,应该在这里解决。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-29
  • 2017-04-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2015-02-11
相关资源
最近更新 更多