Python - 處理 Word 文件



要閱讀 word 文件,我們可以藉助名為 docx 的模組。我們首先安裝 docx,如下所示。然後編寫一個程式,使用 docx 模組中的不同函式,按段落讀取整個檔案。

我們使用以下命令將 docx 模組匯入我們的環境。

 pip install docx 

在以下示例中,我們將 word 文件的內容讀入一個段落,並最終打印出所有段落文字。

import docx

def readtxt(filename):
    doc = docx.Document(filename)
    fullText = []
    for para in doc.paragraphs:
        fullText.append(para.text)
    return '\n'.join(fullText)

print (readtxt('path\Tutorialspoint.docx'))

當執行上述程式時,將得到以下輸出 −

Tutorials Point originated from the idea that there exists a class of readers who respond 
better to online content and prefer to learn new skills at their own pace from the comforts 
of their drawing rooms. 

The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, 
we worked our way to adding fresh tutorials to our repository which now proudly flaunts 
a wealth of tutorials and allied articles on topics ranging from programming languages 
to web designing to academics and much more.

讀取單個段落

我們可以使用 paragraph 屬性從 word 文件中讀取特定段落。在以下示例中,我們只從 word 文件中讀取第二個段落。

import docx

doc = docx.Document('path\Tutorialspoint.docx')
print len(doc.paragraphs)

print doc.paragraphs[2].text

當執行上述程式時,將得到以下輸出 −

The journey commenced with a single tutorial on HTML in 2006 and elated by the response 
it generated, we worked our way to adding fresh tutorials to our repository 
which now proudly flaunts a wealth of tutorials and allied articles on topics 
ranging from programming languages to web designing to academics and much more.
廣告
© . All rights reserved.