2013-12-21 2 views
1

저는 파이썬에서 처리해야하는 XML을 상속 받았습니다. xml.etree.cElementTree을 사용하고 있으며 빈 요소 다음에 나오는 텍스트를 해당 빈 요소의 태그와 연결하는 데 문제가 있습니다. XML은 제가 아래 붙여 넣은 것보다 훨씬 복잡합니다. 그러나 문제를 명확하게하기 위해 XML을 단순화했습니다 (희망합니다!).xml 텍스트를 파이썬에서 앞의 빈 요소와 어떻게 연관시킬 수 있습니까?

원하는 결과

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

튜플는 문자열을 포함하는 (예를 들어, ('9', '1'))

I가 싶은 결과 이런 딕셔너리이다. 나는이 초기 단계에서 정말로 신경 쓰지 않는다.

test1.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 
: 여기

은 XML이다 당신이 후자의 시도에서 볼 수 있듯이

시도 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): ''} 

, pp.itertext() 두 가지 길이 있습니다. (9, 2)의 값은 (9, 1) 키와 연결하려는 값이고, (9, 2)과 연결하려는 값은 d에 표시되지 않습니다 (zip은 더 이상 p.itertext()을 자릅니다).

도움을 주시면 감사하겠습니다. 미리 감사드립니다.

답변

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 
+0

브릴리언트. 매력처럼 일했습니다. 감사. – user3079064

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.'}