介紹:
我目前正在構建一個關鍵字檢測程式。給它一些“.txt”檔案并回圈遍歷它們,從關鍵字串列中搜索其中的關鍵字,回傳哪些檔案包含該關鍵字。關鍵字存盤在單獨的 python 檔案中的串列中,然后將其匯入到主程式檔案中。
目標:
我想要實作的目標是在決議文本檔案時列印從串列中找到的關鍵字。因此,例如,當它搜索文本檔案并且“Hello”在關鍵字串列中時,我希望輸出為“Hello,found in example_text01.txt”。目前它只是回傳是否找到關鍵字。理想情況下,該程序應如下所示。
示例單詞表:
word_list = ["Demo", "Text", "Hello", "Example"]
示例文本:
Hello how are you?
期望的結果:
"Hello, found in example_text01.txt"
我試過的:
- 嘗試使用
in關鍵字。
運行沒有錯誤,但它會跳過任何帶有關鍵字的文本檔案而不處理它。
- 制作關鍵字檔案純文本并用于
readline()決議文本。
收到以下錯誤:AttributeError: 'list' object has no attribute 'readlines'
keyword撰寫結果檔案時回傳類。
剛回來<class 'ast.keyword'>
代碼:
以下是我目前正在使用的代碼。
keywords = ['Hello', 'Example', 'Keywords']
# Create and open result.txt where results of keyword scan will be stored
with open("/PATH/TO/result.txt", "w") as f:
#Path to the folder the .txt files are stored in within the loop
for filename in listdir("/PATH/TO/txt"):
# Opens all text files as they are processed through the loop
with open('/PATH/TO/CURRENT/TEXT/FILE/IN/txt/example.txt') as currentFile:
text = currentFile.read()
if any(keyword in text for keyword in keywords):
f.write('Keyword found in ' filename[:-4] '\n')
else:
f.write('No keyword in ' filename[:-4] '\n')
代碼的當前輸出是,如果在其中一個文本檔案中找到關鍵字串列中的關鍵字,則如果找到關鍵字,程式將寫入“results.txt”檔案。但是,除此之外,我想找到一種方法來包含找到的關鍵字。任何幫助將不勝感激,謝謝!
uj5u.com熱心網友回復:
只是改變:
if any(keyword in text for keyword in keywords):
f.write('Keyword found in ' filename[:-4] '\n')
else:
f.write('No keyword in ' filename[:-4] '\n')
到:
keywordsFound = [k for k in keywords if k in text] #get all found keywords
if keywordsFound: #if keywords were found
for k in keywordsFound:#for each found keyword
f.write(f'{k}, found in {filename[:-4]}\n') #say it was found
else:
f.write(f'No keyword in {filename[:-4]}\n') #if non-found say it was not found
這將獲取檔案中找到的每個關鍵字,然后寫入另一個檔案。
如果您只想要找到的第一個關鍵字,您可以使用:
keywordsFound = [k for k in keywords if k in text] #get all found keywords
if keywordsFound: #if keywords were found
k = keywordsFound[0] #get only first keyword
f.write(f'{k}, found in {filename[:-4]}\n') #say it was found
else:
f.write(f'No keyword in {filename[:-4]}\n') #if non-found say it was not found
uj5u.com熱心網友回復:
為什么不直接修改底部:
代替
if any(keyword in text for keyword in keywords):
f.write('Keyword found in ' filename[:-4] '\n')
else:
f.write('No keyword in ' filename[:-4] '\n')
...
for k in keywords:
f.write((f'Keyword "{k}" found in ' if keyword in text else 'No keyword in ') filename[:-4] '\n')
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/435956.html
標籤:Python python-3.x 循环 if 语句 文件写入
上一篇:如果函式錯誤。不等于功能不作業
下一篇:如何處理“Noinstancefor(Control.Monad.IO.Class.MonadIO[])”錯誤?
