Python 迭代文件夹结构时匹配文件中的文本
我希望匹配我使用docx从word文档文件中提取的列表中的文本 我想搜索我的文档文件夹文件并打印匹配项Python 迭代文件夹结构时匹配文件中的文本,python,loops,docx,Python,Loops,Docx,我希望匹配我使用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: dri
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_list是word文档的列表,最好的方法是什么?如果我正确理解了您的问题,您希望针对在第二个示例中收集的所有
.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))
谢谢你的帮助,它看起来很有效,但只是给了我一个空的列表,如