題目描述
設計一個命令列工具:
- 輸入一個單字
- 掃描資料夾中的文本檔案(例如莎士比亞作品)
- 對每個檔案輸出:
- 該單字出現次數
- 出現的行號
本質上是簡化版的 grep + 統計。
解題思路
- 遍歷資料夾
- 逐檔逐行讀取
- 做單字邊界匹配(可選擇是否忽略大小寫)
- 記錄次數與行號
Python 參考實作
import os
import re
def search_in_file(path: str, pattern: re.Pattern):
count = 0
lines = []
with open(path, 'r', encoding='utf-8', errors='ignore') as f:
for i, line in enumerate(f, 1):
hits = pattern.findall(line)
if hits:
count += len(hits)
lines.append(i)
return count, lines
def search_in_folder(folder: str, word: str, case_sensitive: bool = False):
flags = 0 if case_sensitive else re.IGNORECASE
pattern = re.compile(r'\\b' + re.escape(word) + r'\\b', flags)
result = {}
for root, _, files in os.walk(folder):
for name in files:
if not name.endswith('.txt'):
continue
path = os.path.join(root, name)
c, ls = search_in_file(path, pattern)
if c > 0:
result[path] = {"count": c, "lines": ls}
return result
複雜度
- 時間:與掃描文本總量成正比
- 空間:與命中行數成正比
需要面試輔助服務?聯絡 OA VO Service
- 📧 Email: [email protected]
- 📱 Phone: +86 17863968105
需要面試真題? 立刻聯繫微信 Coding0201,獲得真題。