使用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、打开目标文档,获取目标段落

        

  1.  
    #-*- coding = utf-8 -*-
  2.  
    import docx
  3.  
    #获取docx文档的所有段落 path : 相对路径包含文档名称
  4.  
    def getpara(path):
  5.  
        try :
  6.  
            docx_temp = docx.Document(path)
  7.  
        except :
  8.  
            print("can't open the docx")
  9.  
            return False
  10.  
        try :
  11.  
            docx_para = docx_temp.paragraphs
  12.  
            print("Succeed getting the para:",path)
  13.  
            return docx_para
  14.  
        except :
  15.  
            print("can't get the ",path," paragraphs")
  16.  
            return False
  1.  
    import re
  2.  
    #从段落中抽取目标段落
  3.  
    def findpara(parpas,str = "Sysname"):
  4.  
    try :
  5.  
        para_list = ["start"]
  6.  
        pattern = re.complie(str)
  7.  
        for para in paras :
  8.  
            match1 = pattern.search(para.text)
  9.  
            if match1 :
  10.  
                para_list.append(para.text)
  11.  
     
  12.  
        para_list.pop(0)
  13.  
        retuen para_list
  14.  
    except :
  15.  
        return False

     2、将查找到的段落写入txt文件

  1.  
    #将制定一个列表的内容写入txt文件
  2.  
    def list2txt(list,name="com") :        #文件名默认为com.txt
  3.  
        if len(list) :
  4.  
        try :
  5.  
            fp = open("com.txt","w")
  6.  
            for cloe in list :
  7.  
                fp.write(cloe)
  8.  
                fp.write("\n")
  9.  
        except :
  10.  
            return False
  11.  
        finally:
  12.  
            fp.close()

    3、工作目录切换与获取指定路径的文档列表

 

  1.  
    import os
  2.  
    #切换工作路径 返回该路径下的文档列表
  3.  
    def set_wd(wd == '0') :
  4.  
        if wd == '0' :
  5.  
            try :
  6.  
               os.chdir(wd)
  7.  
               File_List = os.listdir(wd)
  8.  
               return File_List
  9.  
                except :
  10.  
                print("Error")
  11.  
               return False
  12.  
        else :
  13.  
            try :
  14.  
               wd = os.getcwd()
  15.  
                os.chdir(wd)
  16.  
                print("Using the current path word")
  17.  
                File_List = os.listdir(wd)
  18.  
                return File_List
  19.  
            except :
  20.  
               print("Error")
  21.  
               return False
  22.  
     
  23.  

    charles28437个月前 最后一段 def set_wd(wd == '0') : 这里在python 3.7环境下,语法不正确,应该是 def set_wd(wd='0'):
posted on 2020-02-16 11:56  ein_key  阅读(1917)  评论(0编辑  收藏  举报