温馨提示×

怎么用python批量提取word指定内容

小亿
140
2023-11-09 00:23:41
栏目: 编程语言

要使用Python批量提取Word中的指定内容,你可以使用Python-docx库来处理Word文档。下面是一个示例代码,可以帮助你提取Word文档中的指定内容:

from docx import Document

def extract_content_from_word(file_path, target_text):
    doc = Document(file_path)
    extracted_content = []

    for paragraph in doc.paragraphs:
        if target_text in paragraph.text:
            extracted_content.append(paragraph.text)

    return extracted_content

# 调用示例
file_path = 'path_to_your_word_document.docx'  # 替换为你的Word文档路径
target_text = '指定内容'  # 替换为你要提取的指定内容

extracted_content = extract_content_from_word(file_path, target_text)
for content in extracted_content:
    print(content)

这段代码使用Python-docx库打开指定路径下的Word文档,并遍历文档的每个段落。如果段落中包含目标文本,就将该段落内容添加到extracted_content列表中。最后,打印提取到的内容。

请替换file_path变量为你的Word文档的实际路径,将target_text变量替换为你要提取的指定内容。

0