2017-02-07 55 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