我尝试使用python docx读取word文件内容。例如:附件演示字文件,它包含几个段落。某些段落包含标题编号,例如1.3、1.4.1等。
我的程序是尝试打开docx,并在每个段落中搜索关键字。如果专用段落中存在关键字,请打印出该段落及其标题编号。但是,它无法打印标题编号。例如,我搜索关键字“ wall”,它只打印出带有“ wall”的段落,但没有标题编号1.4.1。我也需要电话号码。
def search_word(filename,word):
#open the word file
document=Document(filename)
#read every paragraph
l=[paragraph.text.encode('utf-8') for paragraph in document.paragraphs]
result=[]
for i in l:
i=i.strip()
i=str(i)
pattern=re.compile(r"(.*)(%s)(.*)"%word,re.I|re.M)
rel=pattern.findall(i)
if len(rel):
result.append(rel)
print(filename+"="*30+"Search Result"+"="*30)
print("-"*150)
for k in result:
for m in k:
print("".join(m).strip('b\'')+"\n"*1)
print("-"*150+"\n"*2)
最后,我找到了一种愚蠢的方法来捕获每个段落的标题及其内容。我先将docx转换为HTML,然后使用beautifulsoup&re搜索我的关键字。
def search_file(file,word):
global output_content
output_content=output_content+"\n"+"*"*30+file.split("\\")[-1]+" Search Result" +"*"*30+"\n"*2
url=file
htmlfile = open(url, 'r', encoding='utf-8')
demo = htmlfile.read()
soup=BeautifulSoup(demo,'lxml')
all_content=soup.find_all(['h1','h2','h3', 'h4', 'h5','p'])
new_list=[]
for item in all_content:
if item.text not in new_list:
new_list.append(item.text)
dic1={} #Build a empty dic to store each clause no, and its detail content from every paragraph
Target=""
content=""
for line in new_list:
line=str(line.replace("\n"," "))
pattern=re.compile(r"(^[1-9].+)") #Judge the paragraph whether start with heading no.
line_no=bool(pattern.search(line))
if line_no: #If the paragraph start with heading no
dic1[Target]=content #Save the conent to heading no. in dic.
Target=line
content=""
continue
else: #if the paragraph is detail, not heading line,
content=content+line+"\n" # save the content
continue
result=[] #The keyword search from the dic item, if the keyword in the item, shall print the dic key and item at the same time.
for value in dic1.values():
pattern=re.compile(r".*%s.*"%word,re.I|re.M)
rel=pattern.findall(value)
if len(rel):
result.append((list(dic1.keys())[list(dic1.values()).index(value)]))
result.append(list(rel))
result.append("\n")
return print_result(file,result)
def print_result(file,nums):全局output_content对我而言如果isinstance(i,list):print_result(文件,i)其他:output_content = output_content + i