繁体   English   中英

Python xml:解析属性

[英]Python xml: parse attributes

我有一份 xml 格式的报纸,我正在尝试解析特定部分。

我的 XML 如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<articles>
   <text>
      <text.cr>
         <pg pgref="1" clipref="1" pos="0,0,2275,3149"/>
         <p type="none">
            <wd pos="0,0,0,0"/>
         </p>
      </text.cr>
      <text.cr>
         <pg pgref="1" clipref="2" pos="0,0,2275,3149"/>
         <p type="none">
            <wd pos="0,0,0,0"/>
         </p>
      </text.cr>
      <text.cr>
         <pg pgref="1" clipref="3" pos="4,32,1078,454"/>
         <p type="none">
            <wd pos="4,32,1078,324">The</wd>
            <wd pos="12,234,1078,450">Newspaper</wd>
         </p>
      </text.cr>

我想解析“The”和“Newspaper”等。 我使用xml.etree.ElementTree ,我的代码如下所示:

import xml.etree.ElementTree as ET

for each_file in entries:
                                               
                        mytree = ET.parse(path.xml)
                        tree = mytree.findall('text')
                        

                        for x in tree:
                            x_ = x.findall('wd')

我设法解析了根和属性,但我不知道如何解决'wd'谢谢你的帮助

将循环更改为

for x in tree:
  x_ = x.findall('.//wd')
  for t in x_:
      if t.text is not None:
          print(t.text)

Output:

The
Newspaper

以下

import xml.etree.ElementTree as ET

xml = '''<?xml version="1.0" encoding="UTF-8"?>
<articles>
   <text>
      <text.cr>
         <pg pgref="1" clipref="1" pos="0,0,2275,3149"/>
         <p type="none">
            <wd pos="0,0,0,0"/>
         </p>
      </text.cr>
      <text.cr>
         <pg pgref="1" clipref="2" pos="0,0,2275,3149"/>
         <p type="none">
            <wd pos="0,0,0,0"/>
         </p>
      </text.cr>
      <text.cr>
         <pg pgref="1" clipref="3" pos="4,32,1078,454"/>
         <p type="none">
            <wd pos="4,32,1078,324">The</wd>
            <wd pos="12,234,1078,450">Newspaper</wd>
         </p>
      </text.cr></text></articles>'''

values = ['The', 'Newspaper']
root = ET.fromstring(xml)
wds = [wd for wd in root.findall('.//wd') if wd.text in values]
for wd in wds:
    print(wd.attrib['pos'])

output

4,32,1078,324
12,234,1078,450

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM