python - 在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'(是的,它区分大小写)
解决方案
您的代码中可能存在逻辑问题。
试试这个更新:
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
推荐阅读
- javascript - android上的谷歌地图没有gms
- javascript - 更改从 Google 表格导入的正/负值的字体颜色
- c# - 如何让 WCF 服务使用 HTTPS 协议
- c# - 将嵌套的 JSON 转换为字典
- woocommerce - 我如何在 Woocommerce 中仅对登录用户应用折扣?
- c - 堆栈帧上缺少注入字符串的某些部分
- javascript - Typescript:Getter 无法返回自定义类型的数组
- c# - 如何说服 Refit 不要添加 xml 序言?
- rest - 确保在后台处理 Flutter 应用程序中的 REST 调用
- swift - 在这种情况下,如何重用 UIPickerView 中的视图?