[英]Counting how many times a regex matches in multiple folders
我最近開始使用 python3,但遇到了一些困難。 希望可以有人幫幫我。
我需要一個 python 函數,它遍歷一個更大文件夾中不同子文件夾中的許多文件,以計算給定單詞出現的總次數(即使一行中有多個)。
所以我應該得到的結果是一個數字,但我實際得到的結果是“沒有結果”。 印刷數百次。
這是代碼,有人能告訴我我做錯了什么嗎? 謝謝!
import so
import re
rootdir = "/path/Desktop/folder"
regex = re.compile(r'\bword\b')
count = 0
for root, dirs, files in os.walk(rootdir):
for file in files:
if regex.findall(file):
count = count + 1
print(count)
else:
print("No results.")
你得到"No results."
一遍又一遍,因為您在每個循環中都打印。
要獲得所需的結果,請執行以下操作:
import os
import re
rootdir = "/path/Desktop/folder"
regex = re.compile(r'\bword\b')
count = 0
for root, dirs, files in os.walk(rootdir):
for file in files:
if regex.findall(file):
count = count + 1
if count > 0:
print(count)
else:
print("No results.")
沒有正則表達式,允許部分匹配:
import os
rootdir = "/path/Desktop/folder"
searched_word = "word"
count = 0
for root, dirs, files in os.walk(rootdir):
for file in files:
if searched_word in file:
count = count + 1
if count > 0:
print(count)
else:
print("No results.")
你也可以試試這個正則表達式,如果它是內部的,換句話說就是抓住這個詞
\b(\w*word\w*)\b
您不是在閱讀文件中的文本,而實際上只是在文件名中查找單詞。 您可以執行 print(file) 以查看您正在查看的內容。
import os
import re
rootdir = "/path/Desktop/folder"
regex = re.compile(r'\bword\b')
count = 0
for root, dirs, files in os.walk(rootdir):
for filename in files:
with open(f'{path}/{filename}','r'):
for line in f.readlines():
if regex.findall(line):
count +=1
print(count)
但是,這可能不是處理大文件時的最佳方法。
我推斷您要做的是遞歸地查找目錄結構中的任何和所有文本文件,打開它們進行閱讀,計算每個文件中正則表達式匹配的出現次數並計算所有出現的總次數文件。
在這種情況下,您忽略了在發現每個文件時實際打開它,並且您實際上並沒有計算文件內容中的出現次數 - 您正在嘗試將正則表達式與文件名進行匹配。 此外,如果當前文件名至少包含一個匹配項,則您當前只會將count
加一。 在我看來,無論在文件內容中發現了多少次出現,您都想增加count
。
這就是我可能會寫的方式。 我還沒有測試過這個,但我認為它應該有效:
import re
from pathlib import Path
pattern = r"\bword\b"
def get_occurrences(path):
return len(re.findall(pattern, path.read_text()))
total = sum(map(get_occurrences, Path("/path/Desktop/folder").rglob("*.txt")))
if total:
print(f"Total number of occurrences: {total}"))
else:
print("No occurrences")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.