我必須創建一個搜索引擎,它將在包含文本檔案的目錄(檔案夾)中搜索特定單詞。
例如,假設我們正在某個名為 X 的目錄中搜索“機器”一詞。我想要實作的是掃描 X 及其子目錄中的所有 txt 檔案。
我在呼叫 Python 物件時超出了最大遞回深度。
import os
from pathlib import Path
def getPath (folder) :
fpath = Path(folder).absolute()
return fpath
def isSubdirectory (folder) :
if folder.endswith(".txt") == False :
return True
else :
return False
def searchEngine (folder, word) :
path = getPath(folder)
occurences = {}
list = os.listdir (path) #get a list of the folders/files in this path
#assuming we only have .txt files and subdirectories in our folder :
for k in list :
if isSubdirectory(k) == False :
#break case
with open (k) as file :
lines = file.readlines()
for a in lines :
if a == word :
if str(file) not in occurences :
occurences[str(file)] = 1
else :
occurences[str(file)] = 1
return occurences
else :
return searchEngine (k, word)
uj5u.com熱心網友回復:
幾點:
- 運行您的代碼時,我無法重建遞回錯誤。但是我認為您在這里遇到了問題:-
list = os.listdir(path)這僅給您相對檔案/路徑名,但是一旦您不在?opencwd - 我認為該
return陳述句放錯了位置:它在第一個 txt 檔案之后回傳? - Python 為遞回遍歷路徑提供了現成的解決方案:
os.walk()和glob.glob():Path.rglob()為什么不使用它們? Path.absolute()沒有記錄,我不會使用它。你可以Path.resolve()改用嗎?- 您
occurences對遞回步驟中回傳的內容不執行任何操作:我認為您應該在檢索主字典后更新它? - 不要
list用作變數名 - 您正在覆寫對內置list().
這是一個建議Path.rglob():
from pathlib import Path
def searchEngine(folder, word):
occurences = {}
for file in Path(folder).rglob('*.txt'):
key = str(file)
with file.open('rt') as stream:
for line in stream:
count = line.count(word)
if count:
if key not in occurences:
occurences[key] = count
else:
occurences[key] = count
return occurences
如果您想為自己實作遞回,那么您可以執行以下操作:
def searchEngine(folder, word) :
base = Path(folder)
occurences = {}
if base.is_dir():
for path in base.iterdir():
occurences.update(searchEngine(path, word))
elif base.suffix == '.txt':
with base.open('rt') as stream:
key = str(base)
for line in stream:
count = line.count(word)
if count:
if key not in occurences:
occurences[key] = count
else:
occurences[key] = count
return occurences
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/466827.html
上一篇:單擊導航中的鏈接后選單未關閉
下一篇:所選選項回傳標簽而不是文本值
