欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于Python繪制鍵盤按鍵使用次數(shù)的熱力圖

 更新時(shí)間:2024年04月22日 10:08:13   作者:大鯨魚crush  
這篇文章主要為大家詳細(xì)介紹了如何使用Python繪制鍵盤按鍵使用次數(shù)的熱力圖,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

前言

刷掘金時(shí)候偶然看到了記錄下今天敲了多少下鍵盤,但是博主只是展示了統(tǒng)計(jì)出的鍵盤使用次數(shù),因此想到在這個(gè)idea上小改一下,實(shí)現(xiàn)鍵盤按鍵的熱力圖展示。

思路分析

  • 按鍵記錄 這里可以使用 pynput 來偵聽鍵盤事件并記錄每次按鍵的計(jì)數(shù)。
  • 數(shù)據(jù)存儲 使用一個(gè)字典來存儲按鍵次數(shù),其中鍵代表鍵盤鍵,值代表按下的次數(shù)。
  • 可視化 使用 matplotlib 和 seaborn 庫可視化熱力圖。 您將把字典中的計(jì)數(shù)映射到色標(biāo),該色標(biāo)將顯示在代表 108 鍵鍵盤的布局上。
  • 實(shí)時(shí)顯示 使用 tkinter 庫實(shí)時(shí)更新熱圖

具體實(shí)現(xiàn)

設(shè)置環(huán)境

首先安裝一些Python庫。pynput庫將允許我們捕獲鍵盤事件,matplotlib將使我們能夠創(chuàng)建熱圖可視化,tkinter將用于構(gòu)建GUI。:

pip install pynput matplotlib tk

定義按鍵字典

這里我們需要預(yù)先使用字典存儲鍵盤中的全部按鍵的名字。

key_layout = [
    ['Esc', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'PrtSc', 'Scroll', 'Pause'],
    ['`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', 'Backsp', '', ''],
    ['Tab', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', '\', '', ''],
    ['Caps', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', "'", 'Enter', '', '', ''],
    ['Shift', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'Shift', '', '', '', ''],
    ['Ctrl', 'Win', 'Alt', 'Space', 'Alt', 'Fn', 'Menu', 'Ctrl', '', '', '', '', '', '', '', '']
]

捕獲鍵盤輸入

pynput可以以非阻塞方式監(jiān)聽鍵盤事件。保證程序可以在監(jiān)聽按鍵時(shí)繼續(xù)進(jìn)行其他任務(wù)(如更新GUI)。以下是如何為鍵盤事件設(shè)置監(jiān)聽器:

from pynput.keyboard import Listener

def on_press(key):
    try:
        key_name = key.char.lower() if hasattr(key, 'char') and key.char is not None else key.name.lower()
        if key_name in key_counts:
            key_counts[key_name] += 1
            update_heatmap()
    except AttributeError:
        pass

listener = Listener(on_press=on_press)
listener.start()

存儲和加載數(shù)據(jù)

這里我增加了個(gè)數(shù)據(jù)存儲功能,在每次關(guān)閉的時(shí)候?qū)?shù)據(jù)存儲到本地json文件中。load_data()save_data()函數(shù)處理從文件中讀取和寫入數(shù)據(jù):

import json
import os

def load_data():
    if os.path.exists('keyboard_data.json'):
        with open('keyboard_data.json', 'r') as file:
            return json.load(file)
    else:
        return {}

def save_data(data):
    with open('keyboard_data.json', 'w') as file:
        json.dump(data, file, indent=4)

使用Matplotlib創(chuàng)建熱圖

使用matplotlib來生成我們的熱圖:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
heatmap = ax.imshow(np.zeros((6, 16)), cmap='hot', interpolation='nearest')

for y, row in enumerate(key_layout):
    for x, key in enumerate(row):
        ax.text(x, y, key, ha='center', va='center', color='white')

使用Tkinter構(gòu)建GUI

這里使用了tkinter來構(gòu)建一個(gè)簡單的UI界面。

import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

root = tk.Tk()
root.title("Keyboard Heatmap")
canvas = FigureCanvasTkAgg(fig, master=root)
canvas_widget = canvas.get_tk_widget()
canvas_widget.pack()
root.mainloop()

界面效果如下:

處理程序關(guān)閉

為了確保在應(yīng)用程序關(guān)閉時(shí)保存數(shù)據(jù),我們連接到窗口的關(guān)閉事件:

def on_close():
    save_data(data)
    root.destroy()

root.protocol("WM_DELETE_WINDOW", on_close

)

最終效果

最終代碼匯總

import tkinter as tk
from pynput.keyboard import Listener
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
import json
from datetime import datetime
import os

key_layout = [
    ['Esc', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'PrtSc', 'Scroll', 'Pause'],
    ['`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', 'Backsp', '', ''],
    ['Tab', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '[', ']', '\', '', ''],
    ['Caps', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', "'", 'Enter', '', '', ''],
    ['Shift', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '/', 'Shift', '', '', '', ''],
    ['Ctrl', 'Win', 'Alt', 'Space', 'Alt', 'Fn', 'Menu', 'Ctrl', '', '', '', '', '', '', '', '']
]

# Initialize key counts, ignoring empty strings
key_counts = {key.lower(): 0 for row in key_layout for key in row if key}

# File for storing the data
data_file = 'keyboard_data.json'

# Load historical data
def load_data():
    if os.path.exists(data_file):
        with open(data_file, 'r') as f:
            return json.load(f)
    else:
        return {}

# Save data
def save_data(data):
    with open(data_file, 'w') as f:
        json.dump(data, f, indent=4)

# Current date
current_date = datetime.now().strftime("%Y-%m-%d")
data = load_data()
if current_date not in data:
    data[current_date] = {key.lower(): 0 for row in key_layout for key in row if key}

# Setup the matplotlib figure and axis
fig, ax = plt.subplots(figsize=(12, 3))
heatmap = ax.imshow(np.zeros((6, 16)), cmap='hot', interpolation='nearest', vmin=0, vmax=10)
ax.set_xticks([])
ax.set_yticks([])

# Adding key labels to the heatmap
for y, row in enumerate(key_layout):
    for x, key in enumerate(row):
        if key:
            ax.text(x, y, key, ha='center', va='center', color='white', fontsize=8)

# Function to update the heatmap
def update_heatmap():
    data_array = np.array([[data[current_date].get(key.lower(), 0) for key in row] for row in key_layout])
    heatmap.set_data(data_array)
    canvas.draw_idle()

# Key press callback
def on_press(key):
    try:
        key_name = key.char.lower() if hasattr(key, 'char') and key.char is not None else key.name.lower()
        if key_name in data[current_date]:
            data[current_date][key_name] += 1
            root.after(1, update_heatmap)
    except AttributeError:
        pass

# Setup the tkinter window
root = tk.Tk()
root.title("Keyboard Heatmap")

# Embed the matplotlib figure in the tkinter window
canvas = FigureCanvasTkAgg(fig, master=root)
canvas_widget = canvas.get_tk_widget()
canvas_widget.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

# Start listening to the keyboard in the background
listener = Listener(on_press=on_press)
listener.start()

# Shutdown hook to save data when the program is closed
def on_close():
    save_data(data)
    root.destroy()

root.protocol("WM_DELETE_WINDOW", on_close)

# Start the tkinter main loop
root.mainloop()

到此這篇關(guān)于基于Python繪制鍵盤按鍵使用次數(shù)的熱力圖的文章就介紹到這了,更多相關(guān)Python鍵盤使用次數(shù)熱力圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • freeswitch開源通信 python模塊介紹

    freeswitch開源通信 python模塊介紹

    freeswitch支持多種語言的業(yè)務(wù)開發(fā),包括C/C++,java,python,js,lua,Golang等等。freeswitch在使用python做業(yè)務(wù)開發(fā)時(shí),有倆種接入方式,一種是ESL接口,另一種是mod_python模塊。本文主要介紹的是fs內(nèi)部的mod_python語言支持模塊,需要的朋友可以參考下面文章內(nèi)容
    2021-09-09
  • Python 使用自定義時(shí)間滾動日志處理器

    Python 使用自定義時(shí)間滾動日志處理器

    本教程介紹了如何使用Python的logging模塊和自定義的日志處理器來按時(shí)間滾動日志文件,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-12-12
  • Python封裝MySQL操作工具類

    Python封裝MySQL操作工具類

    在Python中對MySQL的操作通常通過mysql-connector-python或PyMySQL庫進(jìn)行,本文主要為大家介紹了一個(gè)簡單的對MySQL操作的封裝示例,希望對大家有所幫助
    2025-01-01
  • OpenCV實(shí)現(xiàn)直線檢測

    OpenCV實(shí)現(xiàn)直線檢測

    這篇文章主要為大家詳細(xì)介紹了OpenCV實(shí)現(xiàn)直線檢測,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • 深度學(xué)習(xí)環(huán)境配置之Anaconda安裝和pip源方式

    深度學(xué)習(xí)環(huán)境配置之Anaconda安裝和pip源方式

    這篇文章主要介紹了深度學(xué)習(xí)環(huán)境配置之Anaconda安裝和pip源方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • python提取xml里面的鏈接源碼詳解

    python提取xml里面的鏈接源碼詳解

    在本篇文章里小編給大家整理的是關(guān)于python提取xml里面的鏈接的相關(guān)知識點(diǎn)內(nèi)容,需要的朋友們可以學(xué)習(xí)下。
    2019-10-10
  • 使用Python FastAPI構(gòu)建Web服務(wù)的實(shí)現(xiàn)

    使用Python FastAPI構(gòu)建Web服務(wù)的實(shí)現(xiàn)

    這篇文章主要介紹了使用Python FastAPI構(gòu)建Web服務(wù)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • python中字符串String及其常見操作指南(方法、函數(shù))

    python中字符串String及其常見操作指南(方法、函數(shù))

    String方法是用來處理代碼中的字符串的,它幾乎能搞定你所遇到的所有字符串格式,下面這篇文章主要給大家介紹了關(guān)于python中字符串String及其常見操作(方法、函數(shù))的相關(guān)資料,需要的朋友可以參考下
    2022-04-04
  • python 定時(shí)器,實(shí)現(xiàn)每天凌晨3點(diǎn)執(zhí)行的方法

    python 定時(shí)器,實(shí)現(xiàn)每天凌晨3點(diǎn)執(zhí)行的方法

    今天小編就為大家分享一篇python 定時(shí)器,實(shí)現(xiàn)每天凌晨3點(diǎn)執(zhí)行的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-02-02
  • python小程序?qū)崿F(xiàn)刷票功能詳解

    python小程序?qū)崿F(xiàn)刷票功能詳解

    這篇文章主要介紹了python小程序?qū)崿F(xiàn)刷票功能詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07

最新評論