在迭代文件夹结构时匹配文件中的文本

match text within a file while iterating the folder structure

我正在寻找匹配我使用 docx 从 word 文档文件中提取的列表中的文本 我想搜索我的文档文件夹文件并打印匹配项

import docx
import os
d = docx.Document('C:\Users\name\document.docx')
tables = list(d.tables)

tbl = d.tables
drive_firmware_list = []
for table in tables:
    for row in table.rows:
        drive_firmware_list.append(row.cells[0].text)

print(drive_firmware_list)

我使用上面的代码从文档中提取了需求信息

directory = ('C:\Users\name\My_reports')
doc_list =[]

count = 0
for subdir, dirs, files in os.walk(directory):
    for file in files:
        # print (os.path.join(subdir, file))
        filepath = subdir + os.sep + file
        if filepath.endswith(".docx"):
            if '2020'in filepath:# only selcting 2020 files 
                count +=1
                doc_list.append(filepath)

#use "\n" .join to print the list on seperate lines
# print('\n'.join(doc_list))

for file in doc_list:
    if 'Optimize' not in file:
        doc_list.remove(file)
print ('\n'.join(doc_list))

我迭代了文件夹并提取了所有 word doc 文件并删除了我不需要的文件,使用上面的代码我想针对 drive_firmware_list 数组迭代 doc_list,并打印匹配项。 考虑到 doc_list 是一个单词文档列表,最好的方法是什么?

如果我对你的问题的理解正确,你想运行第一个示例中的代码与你在第二个示例中收集的所有 .docx 文件进行对比?

你可以为此使用一个函数:

import docx
import os

def extract_firmware_list(filename):
    d = docx.Document(filename)

    drive_firmware_list = []
    for table in d.tables:
        for row in table.rows:
            drive_firmware_list.append(row.cells[0].text)

    return drive_firmware_list

# i'm leaving out the code to build up the doc_list

for filename in doc_list:
    print(extract_firmware_list(filename))