2017-02-07 76 views
1

我想按照它们写入Word文档的顺序来处理对象。我遇到的对象是段落,段落中的文字,段落中运行的文本,表格单元格中的表格和段落。到目前为止,我有两个有用的程序。 通过文件段落并获得该段文本的文件;存储在由[段落号]索引的列表中。同样的程序能够从运行中收集文本;存储在由[段落#] [运行#]索引的2D列表中,但是我没有发现运行比段落的整个文本更有用。 我的第二个程序遍历整个文档并找到表格。当它有一个表格时,它会逐行浏览单元格中的行,单元格和段落。在docx中按顺序处理对象

现在,这些看起来像是我的目标的伟大构建块。我想按顺序收集文字。抽象地说,就好像闪烁的文本光标被一个人按住键盘上的右箭头命令移动一样。当文本光标在对象上移动时,它将通过标记对象的#号和对象类型的多个索引来存储它们。

说我有子函数paragraph_read和table_read。说文档有这个顺序的对象:。我想通过这些和执行我的子功能,以这个顺序:paragraph_read,paragraph_read,table_read,paragraph_read

我想知道我的程序是否可以通过像光标滑动右对象的文档对象移动。

帮助很大程度上appreaciated。谢谢。

克里斯

+0

有一些讨论,并在此代码,描述那个:https://github.com/python-openxml/python-docx/issues/40。请务必在最后进行一些更新以适应最新版本。 – scanny

+0

这正是我想要做的。感谢指针。 -Chris – Chris

+0

@scanny我无法理解此页面上的代码。你能说说我吗?或者给我一些关于如何使用它的提示? – Chris

回答

3

你需要这个功能添加到您的代码方便的地方:

from docx.document import Document 
from docx.oxml.table import CT_Tbl 
from docx.oxml.text.paragraph import CT_P 
from docx.table import _Cell, Table 
from docx.text.paragraph import Paragraph 


def iter_block_items(parent): 
    """ 
    Yield each paragraph and table child within *parent*, in document 
    order. Each returned value is an instance of either Table or 
    Paragraph. *parent* would most commonly be a reference to a main 
    Document object, but also works for a _Cell object, which itself can 
    contain paragraphs and tables. 
    """ 
    if isinstance(parent, Document): 
     parent_elm = parent.element.body 
    elif isinstance(parent, _Cell): 
     parent_elm = parent._tc 
    else: 
     raise ValueError("something's not right") 

    for child in parent_elm.iterchildren(): 
     if isinstance(child, CT_P): 
      yield Paragraph(child, parent) 
     elif isinstance(child, CT_Tbl): 
      yield Table(child, parent) 

然后你使用这样的:

document = Document('my_document.docx') 

for block_item in iter_block_items(document): 
    if isinstance(block_item, Paragraph): 
     do_paragraph_thing(paragraph=block_item) 
    elif isinstance(block_item, Table): 
     do_table_thing(table=block_item) 
    else: 
     # raise an exception or do nothing or whatever. This branch would 
     # only be reached on an unforeseen error. 
+0

我得到一个属性错误:'CT_Document'对象没有属性'_body' – Chris

+0

@Chris对不起,应该是没有前导下划线的'body'。我更新了代码。 – scanny

+0

你是很大的帮助。它确实与该修改一起工作。我想出了do_paragraph_thing(block_item,Paragraph)是我的函数的占位符,以及存储在block_item中的内容。我仍然在努力修整整个程序,但是这个程序的重要部分已经被扣除。有问题的身体几乎适合! :) – Chris