在word文档中搜索单词并打印出包含该单词的文件名



嘿,所以我是Python的新手,我想制作一个脚本,如果一个文件在单词document中包含某个单词,则从大目录中的docx文档列表中检索文件名。

这是我的代码下面到目前为止

import os
import docx2txt
os.chdir('C:/Users/epicr/Desktop/Python Stuff/LAB FILES')
text= ''
files = []
for file in os.listdir('C:/Users/epicr/Desktop/Python Stuff/LAB FILES'):
if file.endswith('.docx'):
files.append(file)
for i in range(len(files)):
text += docx2txt.process(files[i])
if text == str('VENTILATION RATIO'):
print (i)

我的想法是将所有这些docx文档转换为txt文件,然后在文件中搜索包含"通风比率"的单词。如果该单词存在于文件中,则将打印包含该文件的文件名。

然而,输出不会打印出任何内容。我知道,在至少一个Word文档中,中有一个词:"通风比率"(是的,它区分大小写(

您的代码中可能存在逻辑问题。

尝试此更新:

import os
import docx2txt
os.chdir('C:/Users/epicr/Desktop/Python Stuff/LAB FILES')
text= ''
files = []
for file in os.listdir('C:/Users/epicr/Desktop/Python Stuff/LAB FILES'):
if file.endswith('.docx'):
files.append(file)
for i in range(len(files)):
text = docx2txt.process(files[i])  # text for single file
if 'VENTILATION RATIO' in text:
print (i, files[i])  # file index and name

相关内容

最新更新