根据文本文件中字符串"xyz"的外观删除传递给文本文件的最后一个字符输入



所以我一直在摆弄pynput包,并注意到我可以用它创建一个临时的键盘记录程序。我想明白了,但现在我很难处理将击键导出到.txt文件的其他问题。Python 2.7.15

我主要想做的是格式化击键输出,以识别何时按下键="退格"以在按下退格之前删除导出的字符。

from pynput.keyboard import Listener
def write_to_file(key):
letter = str(key)
# letter = letter.replace("u'","") not important
# letter = letter.replace("'", "") not important
if letter == "Key.backspace":
letter = " backspace "
# delete the previous charater and move on with the logging
with open("log.txt", 'a') as f:
f.write(letter)

with Listener(on_press = write_to_file) as lis:
lis.join()

当键盘记录程序运行时,它会将每个击键写入所述log.txt文件

示例:www.googlle_backspace__backspace.com

我显然犯了一个错误,在访问谷歌时写了两个l,我按了两次退格键,所以我在搜索栏中的输入是"www.googl">

现在我想在log.txt文件中格式化它,以便它以某种方式识别字符串">backspace",并删除">backspace"之前的字符。

current log.txt

"www.googlle_backspace__backspace_e.com"

预期log.txt

"www.google.com"

我知道这一定与regex或"re"有关,但我无法理解。

我曾想过注册字符串">backspace",并发送删除提示来删除log.txt中的最后一个字符,但我不知道该怎么做。

类似于:

if letter == "_backspace_":
# delete string "_backspace_" and one character before it.

另一个例子:

log.txt

"My name is Jeff, I am 22_backspace_3 years old"

expected_log.txt

"My My name is Jeff, I am 23 years old"

您可以读取文件的当前内容,然后如果字符是退格,则删除最后一个字符,否则将新字符附加到现有字符串并写入文件。不确定你为什么要做一个键盘记录。

最新更新