2010-01-02 4 views
0

xml 파일을 구문 분석하려고합니다. 태그에있는 텍스트는 성공적으로 (또는 그렇게 보인다) 파싱되지만 일부 태그에 포함되지 않은 텍스트로 출력하려고합니다. 다음 프로그램은 그냥 무시합니다.태그가없는 동안 xml 파일을 구문 분석합니다.

from xml.etree.ElementTree import XMLTreeBuilder 

class HtmlLatex:      # The target object of the parser 
    out = '' 
    var = '' 
    def start(self, tag, attrib): # Called for each opening tag. 
     pass 
    def end(self, tag):    # Called for each closing tag. 
     if tag == 'i': 
      self.out += self.var 
     elif tag == 'sub': 
      self.out += '_{' + self.var + '}' 
     elif tag == 'sup': 
      self.out += '^{' + self.var + '}' 
     else: 
      self.out += self.var 
    def data(self, data): 
     self.var = data 
    def close(self): 
     print(self.out) 


if __name__ == '__main__': 
    target = HtmlLatex() 
    parser = XMLTreeBuilder(target=target) 

    text = '' 
    with open('input.txt') as f1: 
     text = f1.read() 

    print(text) 

    parser.feed(text) 
    parser.close() 

내가 구문 분석하려는 입력의 일부 : <p><i>p</i><sub>0</sub> = (<i>m</i><sup>3</sup>+(2<i>l</i><sub>2</sub>+<i>l</i><sub>1</sub>) <i>m</i><sup>2</sup>+(<i>l</i><sub>2</sub><sup>2</sup>+2<i>l</i><sub>1</sub> <i>l</i><sub>2</sub>+<i>l</i><sub>1</sub><sup>2</sup>) <i>m</i>) /(<i>m</i><sup>3</sup>+(3<i>l</i><sub>2</sub>+2<i>l</i><sub>1</sub>)) }.</p>

+1

를 제공합니다. 물론 _html_ 파서가 필요하지 않습니까? – James

+0

여기에서 생산됩니다 : http://wims.unice.fr/wims/en_tool-linear~linsolver.en.html 솔루션을 얻었을 때 소스를 보면 비슷한 것을 볼 수 있습니다. –

+1

LaTeX 태그를 편집했습니다. ??? –

답변

2

여기에 pyparsing 버전입니다 - 나는 그 의견이 충분히 설명되기를 바랍니다.

src = """<p><i>p</i><sub>0</sub> = (<i>m</i><sup>3</sup>+(2<i>l</i><sub>2</sub>+<i>l</i><sub>1</sub>) """ \ 
     """<i>m</i><sup>2</sup>+(<i>l</i><sub>2</sub><sup>2</sup>+2<i>l</i><sub>1</sub> <i>l</i><sub>2</sub>+""" \ 
     """<i>l</i><sub>1</sub><sup>2</sup>) <i>m</i>) /(<i>m</i><sup>3</sup>+(3<i>l</i><sub>2</sub>+""" \ 
     """2<i>l</i><sub>1</sub>)) }.</p>""" 

from pyparsing import makeHTMLTags, anyOpenTag, anyCloseTag, Suppress, replaceWith 

# set up tag matching for <sub> and <sup> tags 
SUB,endSUB = makeHTMLTags("sub") 
SUP,endSUP = makeHTMLTags("sup") 

# all other tags will be suppressed from the output 
ANY,endANY = map(Suppress,(anyOpenTag,anyCloseTag)) 

SUB.setParseAction(replaceWith("_{")) 
SUP.setParseAction(replaceWith("^{")) 
endSUB.setParseAction(replaceWith("}")) 
endSUP.setParseAction(replaceWith("}")) 

transformer = (SUB | endSUB | SUP | endSUP | ANY | endANY) 

# now use the transformer to apply these transforms to the input string 
print transformer.transformString(src) 

내가 본 어떤 XML처럼

p_{0} = (m^{3}+(2l_{2}+l_{1}) m^{2}+(l_{2}^{2}+2l_{1} l_{2}+l_{1}^{2}) m) /(m^{3}+(3l_{2}+2l_{1})) }. 
3

는 탐색 및 HTML과 XML을 조작, BeautifulSoup 봐, 구문 분석을위한 파이썬 라이브러리가. 그것은 편리한 인터페이스를 가지고 있으며 귀하의 문제를 해결할 수 있습니다 ...

+0

제안 해 주셔서 감사합니다. 나는 그것을 볼 것이다. –

관련 문제