本文目錄一覽:
python如何讀取word文件
def PrintAllParagraphs(doc):
count=doc.Paragraphs.Count
for i in range(count-1,-1,-1):
pr=doc.Paragraphs[i].Range
print pr.Text
app=my.Office.Word.GetInstance()
doc=app.Documents[0]
PrintAllParagraphs(doc)
1.什麼是域
域應用基礎
@staticmethod
def GetInstance():
u”’獲取Word應用程序的Application對象”’
import win32com.client
return win32com.client.Dispatch(‘Word.Application’)
my.Office.Word.GetInstance的方法實現如上,是一個使用win32com操縱Word Com的接口的封裝
所有Paragraph即段落對象,都是通過Paragraph.Range.Text來訪問它的文字的
python處理word文檔
有個庫叫『Python-docx』
安裝之後 python 可以讀寫 word 文檔,就可以拼接了。
如何用python讀取word
使用Python的內部方法open()讀取文本文件
try:
f=open(‘/file’,’r’)
print(f.read())
finally:
if f:
f.close()
如果讀取word文檔推薦使用第三方插件,python-docx 可以在官網上下載
使用方式
# -*- coding: cp936 -*-
import docx
document = docx.Document(文件路徑)
docText = ‘\n\n’.join([
paragraph.text.encode(‘utf-8’) for paragraph in document.paragraphs
])
print docText
python如何讀取word文件中的文本內容並寫入到新的txt文件?
from docx import Document
# 打開 word文件
f = open(‘隨便寫寫行.docx’, ‘rb’)
# 讀取 word文件內容
document = Document(f)
# 打印 word 文檔段落內容2進制列表
# print(document.paragraphs)
# 打開一個txt文檔用來寫入數據
with open(‘result2.txt’, ‘w’) as fw:
# 遍歷 word 段落內容列表
for context in document.paragraphs:
# 以換行符轉換成列表
text = context.text.split(‘\n’)
# 按行寫入,同時換行
fw.write(f”{text[0]}\n”)
# 打印看看效果
print(text[0])
f.close()
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/284884.html