import os
from docx import Document
def search_word_in_docx(path, keyword):
# 获取当前路径下所有文件列表
files = os.listdir(path)
# 筛选出.docx格式的word文档
for file in files:
n = 0
# 若是存在doc格式的word文档,则将其批量转换为.docx格式即可
if file.endswith('.docx') and not file.startswith('-$') and not file.startswith("~$"):
# 打开woord文档
doc = Document(path + file)
# 获取word文档每一行的内容
for i in doc.paragraphs:
if n > 0:
print(i.text)
n = n - 1
if keyword in i.text:
print("-----------------------------\n\n")
print("file:" + file + "\n")
print(i.text)
n = 10 # 往后输出10行
path="" #文件目录
keyword = ""
search_word_in_docx(path,keyword)
|