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

2024-10-01 19:30:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个和用户交流的程序。我用input()从用户那里获取数据,但是,我想告诉用户,例如,如果用户键入脏话,我想在用户键入时打印You are swearing! Delete it immediately!。你知道吗

如您所知,Python首先等待input()完成。我的目标是在完成之前访问input(),然后我可以在用户键入时打印You are swearing! Delete it immediately!。你知道吗

我的程序中有太多的dict和函数,所以我要写一个与我的主要问题相关的例子。你知道吗

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-


Tags: no用户程序youformatinput键入it
1条回答
网友
1楼 · 发布于 2024-10-01 19:30:46

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

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

如果仅对backspace提供有限的支持,则可以编写如下内容:

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()

代码应该通过拆分为更清晰的函数来改进,而且您还应该处理错误消息键入之后的问题,但是我希望您能理解这个想法。你知道吗

希望能有帮助。你知道吗

相关问题 更多 >

    热门问题