Skip to main content
 首页 » 编程设计

python之如何在 input() 进行时访问 input() 函数

2024年10月25日8mq0036

我有一个与用户交流的程序。我正在使用 input() 从用户那里获取数据,但是,我想告诉用户,例如,如果用户输入脏话,我想打印 You are swearing!立即删除它! 而 用户正在输入。

如您所知,首先 Python 会等待 input() 完成。我的目标是在完成之前访问 input() 然后我可以打印 你在发誓!立即删除它! 在用户键入时。

我的程序中有太多指令和函数,所以我将编写一个与我的主要问题相关的示例。

print ("Let's talk..") 
isim=input("What's your name?: ") 
print ("Hi there {}.".format(isim)) 
 
no=["badwords","morebadwords"] 
 
while True: 
    user=input(u">>>{}: ".format(isim)).lower() 
    for ct in user.split(): 
        if ct in no: 
            print ("You are swearing! Delete it immediately! ") 

但它不起作用,因为 Python 首先等待 user 输入完成。如何在用户输入时执行此操作? -Python 3.4,Windows-

请您参考如下方法:

我在这方面没有太多经验,你可能可以找到一些包来做你想做的事。 但一般来说,您需要实现一些行编辑,并在实现它时扫描输入。

getch 的想法功能是使您能够在每次按键后获得回调。该代码是 unix 和 windows 之间的跨平台。 要使用它,只需从 getch 导入 getch。

只对退格键提供有限的支持,你可以这样写:

from getch import getch 
import sys 
  
def is_bad(text): 
    no=["badwords","morebadwords"] 
    words = text.split() 
    for w in words: 
        if w in no: 
            return True 
    return False 
 
def main(): 
    print 'Enter something' 
    text = '' 
    sys.stdout.write('') 
    while True: 
        ch = getch() 
        if ord(ch) == 13: 
            sys.stdout.write('\n') 
            break 
        if ord(ch) == 127: 
            if text: 
                text = text[:-1] 
            # first one to delete, so we add spaces 
            sys.stdout.write('\r' + text + ' ') 
            sys.stdout.write('\r' + text) 
        else: 
            text += ch 
            sys.stdout.write(ch) 
        if is_bad(text): 
            print 'You are writing something bad...' 
    print 'text = %s' % text         
         
         
   
if __name__ == '__main__': 
    main() 

应该通过拆分为更清晰的函数来改进代码,您还应该处理输入错误消息后的情况,但我希望您明白这一点。

希望对您有所帮助。