추가 구문 분석을 위해 포함 된 템플릿 태그를 추출하려면 XML을 구문 분석해야합니다. 파이썬의 정규식을 구부려서 내가 원하는 것을 할 수는 없다.XML의 템플릿 태그를 구문 분석하는 정규 표현식
영어 : 서식 파일 태그가 행의 모든 위치에 포함되어 있으면 해당 특정 행에 대한 모든 XML을 제거하고 템플릿 태그 만 그대로 둡니다.
설명을 위해 테스트 사례를 정리했습니다.
<!-- regex_trial.xml -->
<w:tbl>
<w:tr>
<w:tc><w:t>Header 1</w:t></w:tc>
<w:tc><w:t>Header 2</w:t></w:tc>
<w:tc><w:t>Header 3</w:t></w:tc>
</w:tr>
<w:tr>
<w:tc><w:t>{% for i in items %}</w:t></w:tc>
<w:tc><w:t></w:t></w:tc>
<w:tc><w:t></w:t></w:tc>
</w:tr>
<w:tr>
<w:tc><w:t>{{ i.field1 }}</w:t></w:tc>
<w:tc><w:t>{{ i.field2 }}</w:t></w:tc>
<w:tc><w:t>{{ i.field3 }}</w:t></w:tc>
</w:tr>
<w:tr>
<w:tc><w:t>{% endfor %}</w:t></w:tc>
<w:tc><w:t></w:t></w:tc>
<w:tc><w:t></w:t></w:tc>
</w:tr>
</w:tbl>
이는 원하는 결과 :
#!/usr/bin/env python
import re
f = open('regex_trial.xml', 'r')
orig_xml = f.read()
f.close()
p = re.compile('<w:tr.*?(?P<tag>{%.*?%}).*?</w:tr>', re.DOTALL)
new_xml = p.sub('\g<tag>', orig_xml, 0)
print new_xml
실제 결과 : 여기
<!-- regex_desired_result.xml -->
<w:tbl>
<w:tr>
<w:tc><w:t>Header 1</w:t></w:tc>
<w:tc><w:t>Header 2</w:t></w:tc>
<w:tc><w:t>Header 3</w:t></w:tc>
</w:tr>
{% for i in items %}
<w:tr>
<w:tc><w:t>{{ i.field1 }}</w:t></w:tc>
<w:tc><w:t>{{ i.field2 }}</w:t></w:tc>
<w:tc><w:t>{{ i.field3 }}</w:t></w:tc>
</w:tr>
{% endfor %}
</w:tbl>
내가 테스트에 사용하고 일부 파이썬 코드 여기에 원래의 XML입니다 이 정규식의 :
<!-- regex_trial.xml -->
<w:tbl>
{% for i in items %}
{% endfor %}
</w:tbl>
도움을 주시면 대단히 감사하겠습니다. 이것을 파악할 수 있다면 Django 기반 사이트에서 MS Word docx 파일을 동적으로 생성 할 수 있습니다. 감사!!
업데이트 :이 나는
from xml.etree import ElementTree
import cStringIO as StringIO
TEMPLATE_TAG = 'template_text'
tree = ElementTree.parse('regex_trial.xml')
rows = tree.getiterator('tr')
for row in rows:
for cell in row.getiterator('t'):
if cell.text and cell.text.find('{%') >= 0:
template_tag = cell.text
row.clear()
row.tag = TEMPLATE_TAG
row.text = template_tag
break
output = StringIO.StringIO()
tree.write(output)
xml = output.getvalue()
xml = xml.replace('<%s>' % TEMPLATE_TAG, '')
xml = xml.replace('</%s>' % TEMPLATE_TAG, '')
print xml
모든 도움을 주셔서 감사를 최종 코드 사용되는!
@ user425130 XML/XSLT 파서를 사용 해본 적이 있습니까? –
내가 XSL을 고려해 봤지만, 꽤 못 생겼다. 각 tr을 검사해야한다. tc의 내용을 검사하는 xpath 표현식이 필요하다. 그런 다음 우리가 만지기를 원하지 않는 다른 99 %의 콘텐츠를 처리해야합니다. 응. – aeb6
@ user425130 +1 큰 해결책!Bravo –