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

标签 python input python-3.4

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

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

我的程序中有太多的字典和函数,因此我将编写一个与我的主要问题相关的示例。

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首先等待用户输入完成。如何在用户输入时执行此操作? -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()

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

希望能有所帮助。

关于python - 如何在 input() 正在进行时访问 input() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27991589/

相关文章:

python - 跨多个数据帧的逐元素平均值和标准差

python数组: averaging slope and intercept of datasets

javascript - 当用户更改输入时,React 不会更新组件状态

performance - 从 Perl 中的文本文件读入时跳过标题的最佳方法?

python - 当默认 pip 为 pip2 时,升级 pip3 的正确格式是什么?

python - 什么是 DynamicClassAttribute 以及如何使用它?

python - 模型适用于单个 GPU,但在尝试适用于多个 GPU 时脚本崩溃

python - 返回与 python 重复出现的正则表达式匹配

html - 文本输入字段中的 CSS 错误 - MSIE7

python - 这个过程的逻辑是什么