0

我试图计算用户在输入时按下退格键的次数。我正在使用以下代码,但似乎对我没有任何帮助,TIA 将不胜感激。

word = input()
count = 0
for letter in word:
    if keyboard.is_pressed('\b'):
        count += 1
print(count)
4

2 回答 2

0

安装模块

pip install pynput

并尝试此代码

from pynput.keyboard import Key, Listener

global count
count = 0
def show(key):
    global count
    if(key == Key.backspace):
        count += 1
    if(key == Key.enter):
        return False

with Listener(on_press=show) as listener:
    listener.join()

word = input()
print(count)
于 2021-08-12T19:05:12.890 回答
0

您需要检测按键事件并自己构建输入。输入给你最终结果,这不包含'\ b'

https://www.delftstack.com/howto/python/python-detect-keypress/

伪代码:

b_counter = 0
input = ''
while keypressed not 'Enter'
   if keypressed  is '\b' and len(input) > 0:
     input  == input [-1]
     b_counter += 1
   else:
      input = input + keypressed  

return input, b_counter 
于 2021-08-12T18:47:49.133 回答