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
-
-