導航:首頁 > 編程語言 > python批量讀取word文字

python批量讀取word文字

發布時間:2022-11-29 23:16:33

A. 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')
  1. my.Office.Word.GetInstance的方法實現如上,是一個使用win32com操縱Word Com的介面的封裝

  2. 所有Paragraph即段落對象,都是通過Paragraph.Range.Text來訪問它的文字的

B. 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()

C. 如何在 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)

D. word文字替換批處理之python

 媳婦有無數word文檔要替換,網路後發現沒有現成的方法。

google後沒有太合適的。抄抄寫寫弄個python腳本換目錄下所有word內容,共勉之。

import os

from docx import Document

# 放了一些docx 文件

files_dict ={

"/home/test/a/醫療器械臨床試驗第一版-設計/": "/home/test/a/醫療器械臨床試驗第一版-設計/",

  "/home/test/a/醫療器械臨床試驗第一版-管理制度/": "/home/test/a/醫療器械臨床試驗第一版-管理制度/",

"/home/test/a/醫療器械臨床試驗第一版-SOP/": "/home/test/a/醫療器械臨床試驗第一版-SOP/",

"/home/test/a/目錄/": "/home/test/a/目錄/"

}

replace_dict = {

    "XXGNK":"XZDXGWK",

    "心血管專業": "心臟大血管外科",

    "心血管":"心臟大血管外科",

}

def check_and_change(document, replace_dict):

    """

    遍歷word中的所有 paragraphs,在每一段中發現含有key 的內容,就替換為 value 。

    (key 和 value 都是replace_dict中的鍵值對。)

    """

    for para in document.paragraphs:

        for i in range(len(para.runs)):

            for key, value in replace_dict.items():

                if key in para.runs[i].text:

                    print(key+"-->"+value)

                    para.runs[i].text = para.runs[i].text.replace(key, value)

    for table in document.tables:

        for row in table.rows:

            for cell in row.cells:

                for para in cell.paragraphs:

                    for i in range(len(para.runs)):

                        for key, value in replace_dict.items():

                            if key in para.runs[i].text:

                                print(key+"-->"+value)

                                para.runs[i].text = para.runs[i].text.replace(key, value)

    return document

def main():

    for old_file_path, new_file_path in files_dict.items():

        for name in os.listdir(old_file_path):

            print(name)

            old_file = old_file_path + name

            new_file = new_file_path + name

            if old_file.split(".")[1] == 'docx':

                document = Document(old_file)

                document = check_and_change(document, replace_dict)

                document.save(new_file)

            print("^"*30)

if __name__ == '__main__':

    main()

E. 如何用python讀取word

使用Python的內部方法open()讀取文本文件

try:
f=open('/file','r')
print(f.read())
finally:
iff:
f.close()

如果讀取word文檔推薦使用第三方插件,python-docx 可以在官網上下載

使用方式

#-*-coding:cp936-*-
importdocx
document=docx.Document(文件路徑)
docText=' '.join([
paragraph.text.encode('utf-8')forparagraphindocument.paragraphs
])
printdocText

F. python如何讀取word文件中的文本內容並寫入到新的txt文件

閱讀全文

與python批量讀取word文字相關的資料

熱點內容
android文件分區 瀏覽:368
南京開通數控螺紋編程 瀏覽:290
伺服器與ups用什麼線 瀏覽:967
unix網路命令 瀏覽:48
程序員表白代碼大全可復制 瀏覽:365
手機如何共享web伺服器 瀏覽:956
php介面有什麼用 瀏覽:382
iis如何安裝php 瀏覽:791
k5嗜血魔鍵安卓怎麼調好用 瀏覽:834
建行app中如何添加銀行卡 瀏覽:281
簡便演算法100點 瀏覽:161
如何創新我的世界伺服器 瀏覽:882
戰地怎麼看伺服器地址 瀏覽:348
vue怎麼打包放上伺服器 瀏覽:165
為什麼安卓服夏日活動沒有兔子頭 瀏覽:894
pubg為什麼顯示伺服器連接失敗 瀏覽:650
阿里雲掃碼登錄伺服器 瀏覽:971
化學基礎pdf 瀏覽:896
51單片機晶碼管 瀏覽:281
怎麼查伺服器假死原因日誌在哪看 瀏覽:277