簡體   English   中英

在word文檔中搜索單詞並打印出包含該單詞的文件名?

[英]Search word in word documents and print out the file name that contains that 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM