在不使用額外 lib, pandas 的情形下
import heapq
from collections import Counter
from typing import List, Tuple
# 舊的 code 也要自行補回來喔!!!
def get_top_heavy_ips_native(
filepath: str, top_k: int = 5
) -> List[Tuple[str, int]]:
"""使用純 Python 原生語法計算請求次數前 Top-K 的 IP
特色: 不載入第三方套件、串流逐行讀取、Min-Heap 堆積選取 Top-K。
"""
ip_counter = Counter()
# 1. 串流逐行讀取,避免一次性將大檔案讀入記憶體
with open(filepath, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
# 2. 擷取 IP: split(maxsplit=1) 只切第一刀,節省字串切割開銷
parts = line.split(maxsplit=1)
ip = parts[0]
ip_counter[ip] += 1
# 3. 利用 heapq 以 O(N log K) 複雜度挑出前 K 大的 IP
# Counter.most_common(k) 底層即採用 heapq.nlargest 實作
return ip_counter.most_common(top_k)
# --- 測試執行 ---
if __name__ == "__main__":
top_ips = get_top_heavy_ips_native("server.log", top_k=5)
print("=== [Native Python] Top Heavy IPs ===")
for rank, (ip, count) in enumerate(top_ips, start=1):
print(f"Rank {rank}: {ip} -> {count} 次請求")另一個版本, 採用 pandas
from typing import List, Tuple
import pandas as pd
# 舊的 code 也要自行補回來喔!!!
def get_top_heavy_ips_pandas(
filepath: str, top_k: int = 5, chunksize: int = 100_000
) -> List[Tuple[str, int]]:
"""使用 Pandas 處理巨量日誌並計算 Top-K IP
特色: 分塊載入 (Chunksize)、僅讀取第 0 欄 (IP)、底層向量化加速。
"""
aggregated_counts = pd.Series(dtype="int64")
# 1. 分批串流讀取,sep=' ' 以空白分隔,usecols=[0] 只讀取 IP 欄位
chunks = pd.read_csv(
filepath,
sep=r"\s+",
header=None,
usecols=[0],
names=["ip"],
chunksize=chunksize,
engine="c", # 使用 C 解析引擎以獲得最高速度
)
# 2. 逐批聚合累計
for chunk in chunks:
# 計算當前 Chunk 的頻率分佈
batch_counts = chunk["ip"].value_counts()
# 累加至全域 Series,fill_value=0 處理未出現過的 IP
aggregated_counts = aggregated_counts.add(batch_counts, fill_value=0)
# 3. 取出前 K 大並轉換為標準 List[Tuple[str, int]]
top_series = aggregated_counts.nlargest(top_k).astype(int)
return list(top_series.items())
# --- 測試執行 ---
if __name__ == "__main__":
top_ips = get_top_heavy_ips_pandas("server.log", top_k=5)
print("=== [Pandas] Top Heavy IPs ===")
for rank, (ip, count) in enumerate(top_ips, start=1):
print(f"Rank {rank}: {ip} -> {count} 次請求")