- Python - 文字處理
- Python - 文字處理簡介
- Python - 文字處理環境
- Python - 字串不可變性
- Python - 對行進行排序
- Python - 重新格式化段落
- Python - 統計段落中的標記
- Python - 二進位制 ASCII 轉換
- Python - 字串作為檔案
- Python - 從後向前讀取檔案
- Python - 篩選重複詞語
- Python - 從文字中提取電子郵件
- Python - 從文字中提取 URL
- Python - 美化列印
- Python - 文字處理狀態機
- Python - 首字母大寫並翻譯
- Python - 分詞
- Python - 移除停用詞
- Python - 同義詞和反義詞
- Python - 文字翻譯
- Python - 詞彙替換
- Python - 拼寫檢查
- Python - WordNet 介面
- Python - 語料庫訪問
- Python - 標記詞語
- Python - 成分和缺塊
- Python - 成分分類
- Python - 文字分類
- Python - 二元語法
- Python - 處理 PDF
- Python - 處理 Word 文件
- Python - 讀取 RSS 提要
- Python - 情感分析
- Python - 搜尋和匹配
- Python - 文字整理
- Python - 文字換行
- Python - 頻率分佈
- Python - 文字摘要
- Python - 詞幹演算法
- Python - 約束搜尋
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.
廣告