一会儿内的键盘输入循环,有多个选项



我正在编写一个代码,该代码接受用户输入的单词或短语,然后返回给定单词前后的50个单词的字符串。我希望它能够通过按空格键继续或任何其他按钮退出来滚动浏览找到该单词或短语的实例。我遇到的问题是,如果我使用 keyboard.wait() 方法,我只能允许一种类型的用户输入,但如果我使用我尝试过的任何其他键盘方法,它不会停止我的 while 循环并接受输入。这是我目前正在使用的代码,任何想法都会有所帮助。

while True:
keyboard.wait(" "):
x = (x+1)%len(where_found)
context = contents[where_found[x]-50:where_found[x]+50]
context = " ".join(context)
print(context+"n")

where_found是一个列表,其中包含所搜索单词的所有索引位置,如果是短语,则包含第一个单词。 内容是使用 read().split() 文件读取方法创建的列表。 x 在此代码段之前被分配值 1,并允许代码循环遍历找到它的实例。

编辑: 我已经尝试了readchar.readkey()和msvcrt.getch()都没有成功。当它们到达时,我的 shell 会响应,就好像它在等待输入一样,但从未真正接受过输入。我正在使用Windows和python 3.8.5。

我尝试使用 https://github.com/boppreh/keyboard 中的keyboard.readkey,但它在每次按键时都返回两行。

在此答案中的评论之后,这是一个带有 https://github.com/magmax/python-readchar 的解决方案 它的API要简单得多,并且(在Windows上)它似乎没有阻塞问题。

(contents.txt有这个问题的文字)

import readchar
with open('contents.txt', 'r') as fo:
contents = fo.read().split()
word = input('Please write a word to be searched: ')
print('n### Press space for next match, any other key to exitn')
print('matches found:')
x = -1
delta = 5
while True:
try:
x = contents.index(word, x+1)
context = ' '.join(contents[max(x-delta, 0):x+delta+1])
print(context)
if readchar.readkey() != ' ':
print('nnShutting down...')
break
except:
print('nnthere are no more matches')
break

在终端中测试。 它等待按键,我只按空格。

Please write a word to be searched: and
### Press space for next match, any other key to exit
matches found:
user inputted word or phrase, and then returns a string of
of the 50 words before and after the given word. I
doesn't stop my while loop and accept input. Here is the
before this section of code and allows the code to cycle

there are no more matches

使用其他键进行测试

Please write a word to be searched: and
### Press space for next match, any other key to exit
matches found:
user inputted word or phrase, and then returns a string of
of the 50 words before and after the given word. I

You pressed 'r'
Shutting down...
Please write a word to be searched: and
### Press space for next match, any other key to exit
matches found:
user inputted word or phrase, and then returns a string of

You pressed 'd'
Shutting down...

最新更新