1.將word文檔轉為html操作,通過bs4中的 BeautifulSoup 提取html中所需要的內容
步驟一:下載bs4 和 pydocx 並且引入
pip install bs4
pip install pydocx
# 讀取word中的內容
from pydocx import PyDocX
from bs4 import BeautifulSoup # 將html轉為對象的形式
步驟二:讀取word里面的內容,並且解析
html = PyDocX.to_html("C:\\Users\\Administrator\\Desktop\\test.docx")
soup = BeautifulSoup(html, 'html.parser') """ demo 表示被解析的html格式的內容 html.parser表示解析用的解析器 """ soup.prettify() # 使用prettify()格式化顯示輸出 # print(soup.prettify()) title_list = soup.select("h2>span[style='text-indent:1.25em']", attrs={"style": "text-indent:1.25em"}) content_list = soup.find_all('span', attrs={ "class": "pydocx-left"}) # 指定屬性,查找class屬性為title的標簽元素,注意因為class是python的關鍵字,所以這里需要加個下划線'_' print(len(content_list))
2.讀取word里面的內容,以文本的形式,一段一段的讀出來,通過樣式去獲去文檔里面的內容
步驟一:下載python-docx,並且引入
pip install python-docx
# 引入
from docx import Document
步驟二:讀取word里面的內容
title = ""
content = "" titleArr = [] document = Document("C:\\Users\\Administrator\\Desktop\\test.docx") # 獲取所有段落 all_paragraphs = document.paragraphs for paragraph in all_paragraphs: if paragraph.style.name == 'Normal': content = content + paragraph.text + '\n' else: obj = {"title": title, "content": content} if content != '': titleArr.append(obj) content = "" title = paragraph.text # print(obj)