首页 > 解决方案 > 在word文档中搜索单词并打印出包含该单词的文件名?

问题描述

嘿,所以我是 Python 新手,如果文件在 word 文档中包含某个单词,我想制作一个脚本,从大目录中的 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 文件,然后在文件中搜索包含“VENTILATION RATIO”的单词。如果文件中存在该单词,则将打印包含该文件的文件名。

但是输出不会打印出任何内容。我知道一个事实,至少在一个 Word 文档中,有一个词:'VENTILATION RATIO'(是的,它区分大小写)

标签: pythonfor-loopsearchdirectory

解决方案


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

试试这个更新:

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

推荐阅读