在word文件中查找标题,然后使用python将整个段落复制到新的word文件中

Posted

技术标签:

【中文标题】在word文件中查找标题,然后使用python将整个段落复制到新的word文件中【英文标题】:Finding a heading in word file and copying entire paragraph thereafter to new word file with python 【发布时间】:2018-05-22 01:49:27 【问题描述】:

我有以下情况:

我有数百个包含公司信息的 word 文件。我想在这些文件中搜索特定单词以查找特定段落并将这些段落复制到新的单词文件中。基本上我只需要将原来的几百个文档缩小到更易读的大小。

我拥有的文档位于一个目录中,并带有不同的名称。在它们中的每一个中,我都想提取我需要单独定义的特定信息。

为此,我从以下代码开始,首先将所有文件名写入 .csv 文件:

# list all transcript files and print names to .csv

import os
import csv

with open("C:\\Users\\Stef\\Desktop\\Files.csv", 'w') as f:
    writer = csv.writer(f)
    for path, dirs, files in os.walk("C:\\Users\\Stef\\Desktop\\Files"):
        for filename in files:
            writer.writerow([filename])

这非常有效。接下来我打开 Files.csv 并编辑我需要在每个文档中搜索的关键字的第二列。

请参阅下图了解 .csv 文件的外观:

CSV file

我拥有的几百个单词文件由不同层次的标题构成。我现在想做的是使用我在 .csv 中手动定义的关键字搜索特定标题,然后将以下段落的内容复制到新文件中。我上传了一个 word 文件的摘录,“Presentation”是“标题 1”,“北美”和“中国”是“标题 2”。

Word example

在这种情况下,我想例如搜索“标题 2”“北美”,然后将下面的文本(“总 [...] 稀释基础。)复制到一个新的单词文件中与旧的名称相同,只是添加了“_clean.docx”。

我的代码如下:

import os
import glob
import csv
import docx

os.chdir('C:\\Users\\Stef\\Desktop')

f = open('Files.csv')
csv_f = csv.reader(f)

file_name = []
matched_keyword = []

for row in csv_f:
  file_name.append(row[0])
  matched_keyword.append(row[1])

filelist = file_name
filelist2 = matched_keyword

for i, j in zip(filelist, filelist2):
  rootdir = 'C:\\Users\\Stef\\Desktop\\Files'
  doc = docx.Document(os.path.join(rootdir, i))

在此之后,我找不到任何可行的解决方案。我尝试了几件事,但根本无法成功。我将不胜感激进一步的帮助。

我认为结尾应该再次看起来像这样,但不太确定。

output = 
output.save(i +"._clean.docx")

考虑过以下问题和想法:

Extracting MS Word document formatting elements along with raw text information

extracting text from MS word files in python

How can I search a word in a Word 2007 .docx file?

【问题讨论】:

【参考方案1】:

刚刚为我自己想出了类似的东西,所以这里有一个完整的工作示例。可能是一种更 Pythonic 的方式……

from docx import Document

inputFile = 'soTest.docx'
try:
    doc = Document(inputFile)
except:
    print(
        "There was some problem with the input file.\nThings to check…\n"
        "- Make sure the file is a .docx (with no macros)"
    )
    exit()

outFile = inputFile.split("/")[-1].split(".")[0] + "_clean.docx"

strFind = 'North America'
# paraOffset used in the event the paragraphs are not adjacent
paraOffset = 1
# document.paragraph returns a list of objects
parasFound = []
paras = doc.paragraphs
# use the list index find the paragraph immediately after the known string
# keep a list of found paras, in the event there is more than 1 match
parasFound = [paras[index+paraOffset] 
                for index in range(len(paras))
                if (paras[index].text == strFind)]

# Add paras to new document
docOut = Document()
for para in parasFound:
    docOut.add_paragraph(para.text)

docOut.save(outFile)
exit()

我还添加了输入文件的图像,显​​示北美出现在不止一个地方。

【讨论】:

以上是关于在word文件中查找标题,然后使用python将整个段落复制到新的word文件中的主要内容,如果未能解决你的问题,请参考以下文章

在word如何统计图片数量

批量转换word文档到pdf文件

word 如何批量替换

Python代码保存到word?

将整列整数转换为字符串,在 Pandas 中使用逗号分隔千位

当一个单元格不是数字时,R 包 XLSX 将整列转换为字符串或布尔值