1

我继承了一些需要在 Python 中处理的 xml。我正在使用xml.etree.cElementTree,并且在将空元素之后出现的文本与该空元素的标签相关联时遇到了一些问题。xml 比我在下面粘贴的要复杂得多,但我已经简化了它以使问题更清楚(我希望!)。

我想要的结果是这样的字典:

期望的结果

{(9, 1): 'As they say, A student has usually three maladies:', (9, 2): 'poverty, itch, and pride.'}

元组还可以包含字符串(例如,('9', '1'))。我真的不在乎这个早期阶段。

这是 XML:

测试1.xml

<div1 type="chapter" num="9">
  <p>
    <section num="1"/> <!-- The empty element -->
      As they say, A student has usually three maladies: <!-- Here lies the trouble -->
    <section num="2"/> <!-- Another empty element -->
      poverty, itch, and pride.
  </p>
</div1>

我尝试过的

尝试 1

>>> import xml.etree.cElementTree as ET
>>> tree = ET.parse('test1.xml')
>>> root = tree.getroot()
>>> chapter = root.attrib['num']
>>> d = dict()
>>> for p in root:
    for section in p:
        d[(int(chapter), int(section.attrib['num']))] = section.text


>>> d
{(9, 2): None, (9, 1): None}    # This of course makes sense, since the elements are empty

尝试 2

>>> for p in root:
    for section, text in zip(p, p.itertext()):    # unfortunately, p and p.itertext() are two different lengths, which also makes sense
        d[(int(chapter), int(section.attrib['num']))] = text.strip()


>>> d
{(9, 2): 'As they say, A student has usually three maladies:', (9, 1): ''}

正如您在后一种尝试中看到的那样,p并且p.itertext()是两种不同的长度。的值(9, 2)是我试图与 key 关联(9, 1)的值,而我想要关联的值(9, 2)甚至没有出现d(因为zip截断了 long p.itertext())。

任何帮助,将不胜感激。提前致谢。

4

2 回答 2

1

你试过使用.tail吗?

import xml.etree.cElementTree as ET

txt = """<div1 type="chapter" num="9">
         <p>
           <section num="1"/> <!-- The empty element -->
             As they say, A student has usually three maladies: <!-- Here lies the trouble -->
           <section num="2"/> <!-- Another empty element -->
             poverty, itch, and pride.
         </p>
         </div1>"""
root = ET.fromstring(txt)
for p in root:
    for s in p:
        print s.attrib['num'], s.tail
于 2013-12-21T21:48:45.673 回答
0

我会为此使用BeautifulSoup

from bs4 import BeautifulSoup

html_doc = """<div1 type="chapter" num="9">
  <p>
    <section num="1"/>
      As they say, A student has usually three maladies:
    <section num="2"/>
      poverty, itch, and pride.
  </p>
</div1>"""

soup = BeautifulSoup(html_doc)

result = {}
for chapter in soup.find_all(type='chapter'):
    for section in chapter.find_all('section'):
      result[(chapter['num'], section['num'])] = section.next_sibling.strip()

import pprint
pprint.pprint(result)

这打印:

{(u'9', u'1'): u'As they say, A student has usually three maladies:',
 (u'9', u'2'): u'poverty, itch, and pride.'}
于 2013-12-21T21:59:39.600 回答