【问题标题】:Making Text look like it's being typed in the Python Shell使文本看起来像是在 Python Shell 中输入的
【发布时间】:2014-07-19 17:11:15
【问题描述】:

到目前为止,我想出的唯一方法是清除控制台,然后再显示一个字母的字符串。有什么建议吗?

当前代码:

import os
import time
In=list(input("Text to be displayed: "))
Out=""
Move=[]
print("-")
while len(Move)<len(In):
    Move+=["/","|","\\","-"]
for a in range(0,len(In)):
    if In[a]==" ":
      x=.3
    elif In[a] in ",';:!@#$%^&*()_+-=[]{}":
      x=.25
    elif In[a] in "aeiouzxcvbnm1234567890AEIOUZXCVBNM":
      x=.2
    else:
      x=.15
    os.system('cls')
    Out+=In[a]
    print(Out+Move[a])
    time.sleep(x)
os.system('cls')
print(Out)
input()

【问题讨论】:

    标签: python python-3.x time python-3.3


    【解决方案1】:

    只需使用print()end='' 保持在同一行,并使用flush = True 进行计时:

    import time
    Move+=["/","|","\\","-"]
    text = input('Text to be displayed: ')
    for i in text:
        print(i, end='', flush=True)
        time.sleep(0.1)
    print('\n')
    

    运行如下:

    bash-3.2$ python3.3 test.py
    Text to be displayed: This is a test
    This is a test
    
    bash-3.2$ 
    

    解决您的评论,使用以下代码:

    import time
    Move=["/","|","\\","-",""]
    text = input('Text to be displayed: ')
    for i in range(len(text)):
        print(text[i]+Move[i%5], end='', flush=True)
        time.sleep(0.1)
    print('\n')
    

    【讨论】:

    • 为您修复了打印的括号。 :D
    • 请注意,在 Python3.3 中,您可以使用 print(i, end='', flush=True) 而不是需要 import syssys.stdout.flush()
    • 有没有一种简单的方法可以在末尾添加字符,看起来像是在加载文本,否则代码正是我想要的
    • 看起来像是在加载文本到底是什么意思?
    • 我原来的代码会显示文字:-:h\:he| : hel/ : hell- : 你好
    【解决方案2】:

    如果我对问题的理解正确,您只希望字符串一次出现一个字符,每个字符之间有一个延迟。

    import time
    from sys import stdout
    
    In=list(input("Text to be displayed: "))
    for x in In:
      print(x, end='')
      stdout.flush()
      time.sleep(0.1)
    
    print("\n")
    

    【讨论】:

    • 你能解释一下 stdout.flush() 到底在做什么吗?
    • @JakeTheMC,stdout一般是缓存在内存中的,flush会导致buffer被flush到终端以便用户看到。
    猜你喜欢
    • 2014-07-01
    • 2014-03-12
    • 2016-10-30
    • 2016-08-03
    • 2018-11-05
    • 2015-08-07
    • 1970-01-01
    • 2016-12-14
    • 2013-07-20
    相关资源
    最近更新 更多