【问题标题】:select checkbox tag python选择复选框标记python
【发布时间】:2015-11-20 13:34:39
【问题描述】:

如果有这样的 XML 文档:

<!-- Location -->
<w:t>Lokacioni:</w:t>
<w:t>Kucni:</w:t>
<w:t>Extension:</w:t>
<w:t>Hajvali –Prishtinë</w:t>
<w:t>Rr. “ Dëshmorët e Gollakut “</w:t>
<w:t>P. N. Prishtinë</w:t>

<!-- Date -->
<w:t>Dat:</w:t>
<w:t>Datum:</w:t>
<w:t>Date:</w:t>
<w:t xml:space="preserve"> </w:t>

<!-- Free text - contains time and description-->
<w:t>1.</w:t><w:t>08:05 Aksident trafiku me dëme materiale Audi dhe Kombi te Kisha Graqanic</w:t>

<!-- Checkboxes - 1 means it is checked -->
<w:t>Informuar:PK</w:t><w:checkBox><w:sizeAuto/><w:default w:val="1"/></w:checkBox> 
<w:t>SHME</w:t><w:checkBox><w:sizeAuto/><w:default w:val="0"/></w:checkBox>
<w:t>SHZSH</w:t><w:checkBox><w:sizeAuto/><w:default w:val="0"/></w:checkBox>
<w:t>,Shërbimet tjera</w:t><w:checkBox><w:sizeAuto/><w:default w:val="0"/></w:checkBox>

在 python 中,我想从 .docx 文档生成的 xml 中选择包含复选框的值。我写了这样的代码:

WordNameSpace = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
para_tag = WordNameSpace + 'p'
text_tag = WordNameSpace + 't'
checkBox_tag = WordNameSpace + 'checkBox'
def get_docx_text(path):
    document = zipfile.ZipFile(path)
    xml_content = document.read('word/document.xml')
    document.close()
    tree = XML(xml_content)

    paragraphs = []
    for paragraph in tree.getiterator(checkBox_tag):
        texts = [node.text for node in paragraph.getiterator(text_tag) if node.text]
        if texts:
            paragraphs.append(''.join(texts))

    return paragraphs

results = get_docx_text('test.docx')

print results

当我打印 results 变量时,结果只是 [] ?为什么会这样?

【问题讨论】:

    标签: python json xml


    【解决方案1】:

    您正在遍历此行上的每个复选框标记 (&lt;w:checkBox&gt;):

    for paragraph in tree.getiterator(checkBox_tag):
    

    然后在里面搜索文本标签(&lt;w:t&gt;):

        texts = [node.text for node in paragraph.getiterator(text_tag) if node.text]
    

    但是,如果您查看您的 XML 文档,您的复选框中没有任何文本,例如:

    <w:checkBox><w:sizeAuto/><w:default w:val="0"/></w:checkBox>
    

    所以paragraphs 从来没有添加任何东西,所以get_docx_text 总是返回[]

    仔细检查您真正想要迭代的内容,以及您是否真的想要复选框的兄弟,而不是子复选框。

    【讨论】:

      猜你喜欢
      • 2011-04-14
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多