2013-09-30 2 views
0

저는 Element 클래스의 하위 클래스를 만들려고합니다. 그래도 시작하는 데 문제가 있습니다.lxml 요소 하위 클래스를 만드는 데 어려움이 있습니다.

from lxml import etree 
try: 
    import docx 
except ImportError: 
    from docx import docx 

class File(etree.ElementBase): 
    def _init(self): 
     etree.ElementBase._init(self) 
     self.body = self.append(docx.makeelement('body')) 

f = File() 
relationships = docx.relationshiplist() 
title = 'File' 
subject = 'A very special File' 
creator = 'Me' 
keywords = ['python', 'Office Open XML', 'Word'] 
coreprops = docx.coreproperties(title=title, subject=subject, creator=creator, 
    keywords=keywords) 
appprops = docx.appproperties() 
contenttypes = docx.contenttypes() 
websettings = docx.websettings() 
wordrelationships = docx.wordrelationships(relationships) 
docx.savedocx(f, coreprops, appprops, contenttypes, websettings, 
wordrelationships, 'file.docx') 

나는이 코드에서 출력되는 문서 (호환 기능 팩 2003) 워드의 내 버전을 열고 나에게 다음과 같은 오류를 제공 할 때 :이 파일은 워드 2007의 이전 베타 버전에서 만든 " 이 버전에서는 열 수 없습니다. "File 객체를 docx.newdocument()로 작성된 다른 Element로 대체하면 문서가 정상적으로 출력됩니다. 어떤 아이디어/조언?

+0

생성자에'_init' 대신'__init__'을 사용하셨습니까? 또한,'docx.newdocument()'에 대해 [소스 코드] (https://github.com/mikemaccana/python-docx/blob/master/docx.py)를 검사하여 결과가 어떻게 보이는지 확인할 수 있습니다 . 누락 된 'document' 태그처럼 보입니다. 다만 추측 일뿐입니다. – Michael0x2a

답변

0

File이라는 별도의 클래스를 사용하려는 이유가 실제로 들지 않습니다. Michael0x2a 말했듯이

, 여기

하지만 (나는 Word 2007을 너무 파일을 읽을 수 있다고 생각하지 않습니다)은 문서의 태그를 넣어 did'nt, 그래서 그것은 작동하지 않습니다 것은 수정 된 코드입니다 :

from lxml import etree 
try: 
    import docx 
except ImportError: 
    from docx import docx 

class File(object): 
    def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None, 
        attrnsprefix=None): 
     '''Create an element & return it''' 
     # Deal with list of nsprefix by making namespacemap 
     namespacemap = None 
     if isinstance(nsprefix, list): 
      namespacemap = {} 
      for prefix in nsprefix: 
       namespacemap[prefix] = nsprefixes[prefix] 
      # FIXME: rest of code below expects a single prefix 
      nsprefix = nsprefix[0] 
     if nsprefix: 
      namespace = '{'+nsprefixes[nsprefix]+'}' 
     else: 
      # For when namespace = None 
      namespace = '' 
     newelement = etree.Element(namespace+tagname, nsmap=namespacemap) 
     # Add attributes with namespaces 
     if attributes: 
      # If they haven't bothered setting attribute namespace, use an empty 
      # string (equivalent of no namespace) 
      if not attrnsprefix: 
       # Quick hack: it seems every element that has a 'w' nsprefix for 
       # its tag uses the same prefix for it's attributes 
       if nsprefix == 'w': 
        attributenamespace = namespace 
       else: 
        attributenamespace = '' 
      else: 
       attributenamespace = '{'+nsprefixes[attrnsprefix]+'}' 

      for tagattribute in attributes: 
       newelement.set(attributenamespace+tagattribute, 
           attributes[tagattribute]) 
     if tagtext: 
      newelement.text = tagtext 
     return newelement 

    def __init__(self): 
     super(File,self).__init__() 
     self.document = self.makeelement('document') 
     self.document.append(self.makeelement('body')) 


f = File() 
relationships = docx.relationshiplist() 
title = 'File' 
subject = 'A very special File' 
creator = 'Me' 
keywords = ['python', 'Office Open XML', 'Word'] 
coreprops = docx.coreproperties(title=title, subject=subject, creator=creator, 
    keywords=keywords) 
appprops = docx.appproperties() 
contenttypes = docx.contenttypes() 
websettings = docx.websettings() 
wordrelationships = docx.wordrelationships(relationships) 
docx.savedocx(f.document, coreprops, appprops, contenttypes, websettings, 
wordrelationships, 'file.docx') 
+0

고마워,하지만 문제는 요소 클래스가 __init__을 좋아하지 않는다는 사실에서 비롯된 것 같습니다. 따라서 간단한 생성자 메서드가 작동하지 않는 것 같습니다. http://lxml.de/element_classes.html –

+0

왜 Etree.ElementBase를 확장 하시겠습니까? – edi9999

관련 문제