我對 Python 編程相當陌生,我正在創建一個 Apache 日志決議器。我從“匯入集合”中找到了一個計數器功能。我正在嘗試減少行數,因為目前我正在計算我的 IP 出現次數,如下所示:
if sort == 'ip':
ip_count = []
for match in ip_list:
count = 0
for ip_match in ip:
if match == ip_match:
count = 1
ip_count.append(count)
我的位元組是這樣的:
if desired_output == 'bytes':
cnt_bytes = []
for v in range(len(ip_list)):
tmp = 0
for k in range(len(ip)):
if ip_list[v] == ip[k]:
if bytes[k] == '-':
bytes[k] = 0
tmp = int(bytes[k])
cnt_bytes.append(tmp)
這似乎是不合情理的。
ip_list[] 是唯一 IP 地址的串列。ip_count[] 存盤每個 ip 地址的計數。
有沒有辦法使用 Counter() 函式減少這些代碼行?
uj5u.com熱心網友回復:
您可以使用Counter:
from collections import Counter
with open('access.log') as fp:
ips = []
for row in fp:
ips.append(row.split(maxsplit=1)[0])
counter = Counter(ips)
或者defaultdict:
from collections import defaultdict
with open('access.log') as fp:
counter = defaultdict(int)
for row in fp:
counter[row.split(maxsplit=1)[0]] = 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/434252.html
標籤:Python python-3.x 阿帕奇 日志记录
