Repository navigation
Expand file tree
/
Copy pathkeyboard_count.py
More file actions
84 lines (65 loc) · 2.32 KB
/
Copy pathkeyboard_count.py
File metadata and controls
84 lines (65 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from pynput import keyboard
from collections import Counter
import csv
import time
import os
key_counter = Counter()
HISTORY_FILE = "keyboard_freq.csv"
def pretty_key(key):
try:
return key.char
except AttributeError:
return f"[{key.name}]"
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
def load_history():
"""读取历史 keyboard_freq.csv,累加之前的记录"""
if not os.path.exists(HISTORY_FILE):
return
with open(HISTORY_FILE, "r", encoding="utf-8") as f:
reader = csv.reader(f)
next(reader, None) # 跳过标题
for row in reader:
key, cnt, _ = row
key_counter[key] += int(cnt)
def print_sorted():
total = sum(key_counter.values())
clear()
print(f"实时按键记录(总次数:{total})\n")
print(f"{'按键':<10}{'次数':>8}{'占比(%)':>10}")
print("-" * 28)
for k, cnt in key_counter.most_common(20):
percent = cnt / total * 100 if total > 0 else 0
print(f"{k:<10}{cnt:>8}{percent:>10.2f}")
print("\n(在终端按 Ctrl + C 停止并保存数据)")
def on_press(key):
k = pretty_key(key)
key_counter[k] += 1
print_sorted()
def save_to_file():
sorted_keys = sorted(key_counter.items(), key=lambda x: x[1], reverse=True)
total = sum(key_counter.values())
with open(HISTORY_FILE, "w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerow(["key", "count", "percent"])
for k, cnt in sorted_keys:
percent = cnt / total * 100 if total else 0
writer.writerow([k, cnt, f"{percent:.2f}%"])
print("\n已保存为 keyboard_freq.csv(可直接用 Excel 查看)")
def main():
clear()
print("开始记录键盘按键(历史记录将被自动累加)…")
print("按 Ctrl + C 结束并保存数据。\n")
load_history() # ★★ 加载历史数据(核心修改)
listener = keyboard.Listener(on_press=on_press)
listener.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\n正在保存统计结果…")
save_to_file()
listener.stop()
print("记录结束。")
if __name__ == "__main__":
main()