Ⅰ word圖片和文字文混排內容怎麼用python讀取寫入
Python可以利用python-docx模塊處理word文檔,處理方式是面向對象的。也就是說python-docx模塊會把word文檔,文檔中的段落、文本、字體等都看做對象,對對象進行處理就是對word文檔的內容處理。
二,相關概念
如果需要讀取word文檔中的文字(一般來說,程序也只需要認識word文檔中的文字信息),需要先了解python-docx模塊的幾個概念。
1,Document對象,表示一個word文檔。
2,Paragraph對象,表示word文檔中的一個段落
3,Paragraph對象的text屬性,表示段落中的文本內容。
三,模塊的安裝和導入
需要注意,python-docx模塊安裝需要在cmd命令行中輸入pip install python-docx,如下圖表示安裝成功(最後那句英文Successfully installed,成功地安裝完成,十分考驗英文水平。)
注意在導入模塊時,用的是import docx。
也真是奇了怪了,怎麼安裝和導入模塊時,很多都不用一個名字,看來是很有必要出一個python版本的模塊管理程序python-maven了,本段純屬PS。
四,讀取word文本
在了解了上面的信息之後,就很簡單了,下面先創建一個D:\temp\word.docx文件,並在其中輸入如下內容。
然後寫一段程序,代碼及輸出結果如下:
#讀取docx中的文本代碼示例
import docx
#獲取文檔對象
file=docx.Document("D:\\temp\\word.docx")
print("段落數:"+str(len(file.paragraphs)))#段落數為13,每個回車隔離一段
#輸出每一段的內容
for para in file.paragraphs:
print(para.text)
#輸出段落編號及段落內容
for i in range(len(file.paragraphs)):
print("第"+str(i)+"段的內容是:"+file.paragraphs[i].text)
運行結果:
================ RESTART: F:/360data/重要數據/桌面/學習筆記/readWord.py ================
段落數:13
啊
我看見一座山
雄偉的大山
真高啊
啊
這座山是!
真的很高!
第0段的內容是:啊
第1段的內容是:
第2段的內容是:我看見一座山
第3段的內容是:
第4段的內容是:雄偉的大山
第5段的內容是:
第6段的內容是:真高啊
第7段的內容是:
第8段的內容是:啊
第9段的內容是:
第10段的內容是:這座山是!
第11段的內容是:
第12段的內容是:真的很高!
>>>
總結
以上就是本文關於Python讀取word文本操作詳解的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
Ⅱ python操作word文檔表格
>>>app=my.Office.Word.GetInstance()
>>>doc=app.Documents[0]
>>>printdoc.Name
VBA工具集.doc
>>>doc.Tables.Count
2
>>>table=doc.Tables[1]
>>>table.Cell(1,1).Select()
>>>app.Selection.MoveEnd(Unit=12,Count=4)
4
>>>app.Selection.Cells.Shading.Texture=-10
>>>
1.my.Office.Word.GetInstance()用win32com得到Word的Application對象的實例
2.我所使用的樣本word文件中包含兩個Table第二個Table是想要修改的
3.table.Cell(1,1).Select()用於選中這個樣表的第一個單元格
4.app.Selection.MoveEnd用於獲得向右多選取4個單元格,wdCell=12,用於指示按單元格移動
5.app.Selection.Cells.Shading.Texture = -10用於執行陰影底紋的設置工作,wdTextureDiagonalUp=-10是一個代表斜向右上的底紋樣式的常數
Ⅲ Python批量讀取加密Word文檔轉存txt文本實現
# -*- coding:utf-8 -*-
from win32com import client as wc
import os
key = '文檔密碼'
def Translate(input, output):
# 轉換
wordapp = wc.Dispatch('Word.Application')
try:
doc = wordapp.Documents.Open(input, False, False, False,key)
doc.SaveAs(FileName=output, FileFormat=4, Encoding="gb2312")
doc.Close()
print(input, "完成")
os.remove(input)
# 為了讓python可以在後續操作中r方式讀取txt和不產生亂碼,參數為4
except:
print(input,"密碼錯誤")
if __name__ == '__main__':
#docx文檔物理路徑
path = r"C:Usersdocx"
key = '文檔密碼'
j=0
for file in os.listdir(path):
if '.doc' in file:
name = file.split(".docx")[0]
#輸入文檔物理路徑
input_file = r"C:Usersdocx"+""+file
#輸出文檔物理路徑
output_file=r"C:Users xt"+""+name+".txt"
Translate(input_file, output_file)
j=j+1
print(j)
else:continue
Ⅳ python如何讀取word文件
>>>defPrintAllParagraphs(doc):
count=doc.Paragraphs.Count
foriinrange(count-1,-1,-1):
pr=doc.Paragraphs[i].Range
printpr.Text
>>>app=my.Office.Word.GetInstance()
>>>doc=app.Documents[0]
>>>PrintAllParagraphs(doc)
1.什麼是域
域應用基礎
>>>
@staticmethod
defGetInstance():
u'''獲取Word應用程序的Application對象'''
importwin32com.client
returnwin32com.client.Dispatch('Word.Application')
my.Office.Word.GetInstance的方法實現如上,是一個使用win32com操縱Word Com的介面的封裝
所有Paragraph即段落對象,都是通過Paragraph.Range.Text來訪問它的文字的
Ⅳ 如何在 linux 上使用 Python 讀取 word 文件信息
第一步:獲取doc文件的xml組成文件
import zipfiledef get_word_xml(docx_filename):
with open(docx_filename) as f:
zip = zipfile.ZipFile(f)
xml_content = zip.read('word/document.xml')
return xml_content
第二步:解析xml為樹形數據結構
from lxml import etreedef get_xml_tree(xml_string):
return etree.fromstring(xml_string)
第三步:讀取word內容:
def _itertext(self, my_etree):
"""Iterator to go through xml tree's text nodes"""
for node in my_etree.iter(tag=etree.Element):
if self._check_element_is(node, 't'):
yield (node, node.text)def _check_element_is(self, element, type_char):
word_schema = '99999'
return element.tag == '{%s}%s' % (word_schema,type_char)
Ⅵ 如何在 Linux 上使用 Python 讀取 word 文件信息
請注意,所有的程序在它們第一行都是#!/usr/bin/env/python,也就是說,我們想要Python的解釋器來執行這些腳本。因此,如果你想你的腳本具有執行性,請使用chmod +x your-script.py, 那麼你就可以使用./your-script.py來執行它了(在本文中你將會看到這種方式)
探索platform模塊
platform模塊在標准庫中,它有很多運行我們獲得眾多系統信息的函數。讓我們運行Python解釋器來探索它們中的一些函數,那就從platform.uname()函數開始吧:
>>> import platform
>>> platform.uname()
('Linux', 'fedora.echorand', '3.7.4-204.fc18.x86_64', '#1 SMP Wed Jan 23 16:44:29 UTC 2013', 'x86_64')
如果你已知道linux上的uname命令,那麼你就會認出來這個函數就是這個命令的一個介面。在Python 2上,它會返回一個包含系統類型(或者內核版本),主機名,版本,發布版本,機器的硬體以及處理器信息元組(tuple)。你可以使用下標訪問個別屬性,像這樣:
>>> platform.uname()[0]
'Linux'
在Python 3上,這個函數返回的是一個命名元組:
>>> platform.uname()
uname_result(system='Linux', node='fedora.echorand',
release='3.7.4-204.fc18.x86_64', version='#1 SMP Wed Jan 23 16:44:29
UTC 2013', machine='x86_64', processor='x86_64')
因為返回結果是一個命名元組,這就可以簡單地通過名字來指定特定的屬性,而不是必須記住下標,像這樣:
>>> platform.uname().system
'Linux'
platform模塊還有一些上面屬性的直接介面,像這樣:
>>> platform.system()
'Linux'
>>> platform.release()
'3.7.4-204.fc18.x86_64'
Ⅶ 如何在 Linux 上使用 Python 讀取 word 文件信息
首先下載安裝win32com
from win32com import client as wc
word = wc.Dispatch('Word.Application')
doc = word.Documents.Open('c:/test')
doc.SaveAs('c:/test.text', 2)
doc.Close()
word.Quit()
這種方式產生的text文檔,不能用python用普通的r方式讀取,為了讓python可以用r方式讀取,應當寫成
doc.SaveAs('c:/test', 4)
注意:系統執行完成後,會自動產生文件後綴txt(雖然沒有指明後綴)。
在xp系統下面,應當
open(r'c:\text','r')
wdFormatDocument = 0
wdFormatDocument97 = 0
wdFormatDocumentDefault = 16
wdFormatDOSText = 4
wdFormatDOSTextLineBreaks = 5
wdFormatEncodedText = 7
wdFormatFilteredHTML = 10
wdFormatFlatXML = 19
wdFormatFlatXMLMacroEnabled = 20
wdFormatFlatXMLTemplate = 21
= 22
wdFormatHTML = 8
wdFormatPDF = 17
wdFormatRTF = 6
wdFormatTemplate = 1
wdFormatTemplate97 = 1
wdFormatText = 2
wdFormatTextLineBreaks = 3
wdFormatUnicodeText = 7
wdFormatWebArchive = 9
wdFormatXML = 11
wdFormatXMLDocument = 12
= 13
wdFormatXMLTemplate = 14
= 15
wdFormatXPS = 18
照著字面意思應該能對應到相應的文件格式,如果你是office 2003可能支持不了這么多格式。word文件轉html有兩種格式可選wdFormatHTML、wdFormatFilteredHTML(對應數字 8、10),區別是如果是wdFormatHTML格式的話,word文件裡面的公式等ole對象將會存儲成wmf格式,而選用 wdFormatFilteredHTML的話公式圖片將存儲為gif格式,而且目測可以看出用wdFormatFilteredHTML生成的HTML 明顯比wdFormatHTML要干凈許多。
當然你也可以用任意一種語言通過com來調用office API,比如PHP.
from win32com import client as wc
word = wc.Dispatch('Word.Application')
doc = word.Documents.Open(r'c:/test1.doc')
doc.SaveAs('c:/test1.text', 4)
doc.Close()
import re
strings=open(r'c:\test1.text','r').read()
result=re.findall('\(\s*[A-D]\s*\)|\(\xa1*[A-D]\xa1*\)|\(\s*[A-D]\s*\)|\(\xa1*[A-D]\xa1*\)',strings)
chan=re.sub('\(\s*[A-D]\s*\)|\(\xa1*[A-D]\xa1*\)|\(\s*[A-D]\s*\)|\(\xa1*[A-D]\xa1*\)','()',strings)
question=open(r'c:\question','a+')
question.write(chan)
question.close()
answer=open(r'c:\answeronly','a+')
for i,a in enumerate(result):
m=re.search('[A-D]',a)
answer.write(str(i+1)+' '+m.group()+'\n')
answer.close()
chan=re.sub(r'\xa3\xa8\s*[A-D]\s*\xa3\xa9','()',strings)
#不要(),容易引起歧義。
Ⅷ python讀取word文檔內容
import fnmatch, os, sys, win32com.client
readpath=r'D:\123'
wordapp = win32com.client.gencache.EnsureDispatch("Word.Application")
try:
for path, dirs, files in os.walk(readpath):
for filename in files:
if not fnmatch.fnmatch(filename, '*.docx'):continue
doc = os.path.abspath(os.path.join(path,filename))
print 'processing %s...' % doc
wordapp.Documents.Open(doc)
docastext = doc[:-4] + 'txt'
wordapp.ActiveDocument.SaveAs(docastext,FileFormat=win32com.client.constants.wdFormatText)
wordapp.ActiveDocument.Close()
finally:
wordapp.Quit()
print 'end'
f=open(r'd:\123\test.txt','r')
for line in f.readlines():
print line.decode('gbk')
f.close()
Ⅸ python設置word文檔格式內容
import docx
doc=docx.Document()
整數 0 表示標題是 Title 樣式,這用於文檔的頂部。整數 1 到 45是不同的標題層次,是主要的標題, 45是最低層的子標題。
doc.add_heading('標題0',0)
doc.add_heading('標題1',1)
doc.add_heading('標題2',2)
doc.add_heading('標題3',3)
doc.add_heading('標題4',4)
doc.add_heading('標題5',5)
doc.save('example3.docx')
1# 添加內容
paragraph = doc_.add_paragraph()
run_ = paragraph.add_run("Python 博客")
2# 獲取字體對象
font_ = run_.font
3# 設置下劃線
font_.underline = True
4# 設置加粗
font_.bold = True
5# 設置字體顏色
font_.color.rgb = RGBColor(0xFF,0x00,0x00)
6# 設置字體大小
font_.size = Pt(20)
7# 獲取段落格式
paragraph_format = paragraph.paragraph_format
8# 設置首行縮進
paragraph_format.first_line_indent = Inches(0.2)
9# 設置段前距,單位為英鎊
paragraph_format.space_after = Pt(10)
10# 設置段後距,單位為英鎊
paragraph_format.space_before = Pt(5)
11# 添加表格
table_ = doc_.add_table(rows=2, cols=2, style="Medium Grid 1 Accent 1")
12# 填寫第一行第一列內容
table_.cell(0,0).text ="
13# 填寫第一行第二列內容
table_.cell(0,1).text =""
14# 填寫第二行第一列內容
table_.cell(1,0).text ="描述"
15# 填寫第二行第二列內容
table_.cell(1,1).text =""
16# 添加圖片、width 屬性設置大小
doc_.add_picture(r"/usr/load/download/test.png", width=Inches(4.25))
17# 保存文檔
doc_.save('Python--Word 內容格式.docx')
Ⅹ 如何在 Linux 上使用 Python 讀取 word 文件信息
必須說明:不同於Illustrator、InDesign、CorelDRAW、OpenOffice DRAW、Incscape等工具,Word是流動分頁的,文件內容本身並不存儲分頁結果。具體分頁時斷在哪裡、最後分出多少頁,都需要現場渲染所有的圖文內容之後才能確定。
(簡而言之就是:Word文件中僅包含了一行一行的文本,與頁面設置中指定的頁面尺寸。Word每次打開文件時都會一行一行「擺放」文本數據,發現一頁裝不下了自動新開一頁。當然真正的Word渲染引擎肯定有更復雜的行為。)
從.doc/.docx文件中直接讀出頁面數量,這本身就是個偽命題。所以千萬別在「直接讀取頁面數量」這個方向上尋求方案——軟體開發的技法不好可以改正,但路線錯了必死無疑!
你需要調動一套能夠真的把Word文件的內容渲染出來的工具(支持二次開發的)。只有把Word文件的所有內容渲染成為可以觀看的圖形,才能准確得知頁面的總數。在Linux上很可能LibreOffice可以吧。而在Windows上就當然是用Word本身了。
注意Word的分頁結論是沒有保證的。缺少字體、字形不同、軟體環境不同等各種原因,都會造成不同電腦上打開同一個Word文件的頁數不一致。這一點對伺服器也沒有例外。得到了頁數也只能參考使用,而不要100%信賴。