使用python從docx中抽取特定段落並保存到txt文檔中


https://blog.csdn.net/HUSTER_LC/article/details/79367286

1、遇到問題

    工作中遇到一個問題,需要從dcox文檔中抽取特定的段落;通過對目標對象的調查,發現目標段落的公共特性:具有同樣的段落樣式,並且有共同的開頭Sysname;

    同時存在另外一個問題,存在多個目標文檔,且這些目標文檔存在同一個目標文件夾中

2、解決方案

    先解決問題1:獲取指定路勁下的特定文檔的目標段落

    在解決問題2 :獲取指定路徑下的docx文檔的列表

    1、問題 1 :

        使用python docx 獲取目標文檔的目標段落並使用re模塊查找包含Syname的段落

    2、問題 2:

        使用os改變工作路徑,並獲取特定路勁下的文檔列表,送給1進行處理

3、實施

    1、打開目標文檔,獲取目標段落

#-*- coding = utf-8 -*-
import docx
#獲取docx文檔的所有段落 path : 相對路徑包含文檔名稱
def getpara(path):
    try :
        docx_temp = docx.Document(path)
    except :
        print("can't open the docx")
        return False
    try :
        docx_para = docx_temp.paragraphs
        print("Succeed getting the para:",path)
        return docx_para
    except :
        print("can't get the ",path," paragraphs")
        return False
import re
#從段落中抽取目標段落
def findpara(parpas,str = "Sysname"):
try :
    para_list = ["start"]
    pattern = re.complie(str)
    for para in paras :
        match1 = pattern.search(para.text)
        if match1 :
            para_list.append(para.text)
 
    para_list.pop(0)
    retuen para_list
except :
    return False

2、將查找到的段落寫入txt文件

#將制定一個列表的內容寫入txt文件
def list2txt(list,name="com") :        #文件名默認為com.txt
    if len(list) :
    try :
        fp = open("com.txt","w")
        for cloe in list :
            fp.write(cloe)
            fp.write("\n")
    except :
        return False
    finally:
        fp.close()

3、工作目錄切換與獲取指定路徑的文檔列表

import os
#切換工作路徑 返回該路徑下的文檔列表
def set_wd(wd == '0') :
    if wd == '0' :
        try :
            os.chdir(wd)
            File_List = os.listdir(wd)
            return File_List
            except : 
            print("Error")
            return False
    else :
        try :
            wd = os.getcwd()
            os.chdir(wd)
            print("Using the current path word")
            File_List = os.listdir(wd)
            return File_List
        except :
            print("Error")
            return False

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM