[英]How to print one word at a time on one line?
I want to write code which allows me to print a word out and then it disappears and the next word prints. 我想编写代码,允许我打印出一个单词,然后它消失,下一个单词打印出来。 For example, if I have "Hello World!," the program should print "Hello" then the word disappears and then "World!"
例如,如果我有“Hello World!”,程序应打印“Hello”,然后单词消失,然后“World!” prints and then disappears.
打印然后消失。 I should be able to change the speed of the printing words as well.
我也应该能够改变打印单词的速度。 Currently I was able to figure out how to print characters at a certain speed, but how do I print words one by one?
目前我能够弄清楚如何以一定的速度打印字符,但是如何逐个打印字?
import time
import sys
def print_char(s):
for c in s:
sys.stdout.write( '%s' % c )
sys.stdout.flush()
time.sleep(0.1)
print_char("hello world")
Try this: 尝试这个:
#!/usr/bin/env python3
import sys
import time
data = "this is a sentence with some words".split()
max_len=max([len(w) for w in data])
pad = " "*max_len
for w in data:
sys.stdout.write('%s\r' % pad)
sys.stdout.write("%s\r" % w)
sys.stdout.flush()
time.sleep(0.4)
print
Example, just for the fun of it 例如,只是为了它的乐趣
If words
is a list of strings: 如果
words
是字符串列表:
def print_char(words):
for s in words:
for c in s:
sys.stdout.write('%s' %c)
sys.stdout.flush()
time.sleep(0.1)
# erase the word
sys.stdout.write('\b'*len(s)) # backspace the cursor
sys.stdout.write(' '*len(s)) # overwrite with spaces
sys.stdout.write('\b'*len(s)) # backspace again, to write the next word
Based on the answer to this question: 根据这个问题的答案:
remove last STDOUT line in Python 删除Python中的最后一个STDOUT行
You can do something like this: 你可以这样做:
import time
import sys
CURSER_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
def delay_print(sentence, pause_between_words):
for s in sentence.split(" "):
sys.stdout.write( '%s' % s)
sys.stdout.flush()
time.sleep(pause_between_words)
print(ERASE_LINE + CURSER_UP_ONE)
delay_print("Hello World!", 0.5)
This code will print a word at a time in my terminal, remove the last word and print the next. 此代码将在终端中一次打印一个单词,删除最后一个单词并打印下一个单词。 The last word will be deleted just before termination.
最后一个字将在终止前删除。 Is this how you want it to work?
这是你想要它的工作方式吗? Else let me know.
别告诉我。
EDIT: Noticed that you also wanted to have a delay between each character print. 编辑:注意到您还希望在每个字符打印之间有延迟。 Have updated my code accordingly.
已相应更新我的代码。
EDIT: Based on your comment I removed char by char printing. 编辑:根据您的评论我删除char打印char。
This might not be what youre looking for, and it might not be as fast as some of the other answers, but something that you can do is this: 这可能不是你想要的,它可能没有其他一些答案那么快,但你能做的就是:
import time, os
text = "This is a long sentence that has a lot of words in it.".split()
for i in range(len(text)):
os.system("clear")
print(text[i])
time.sleep(0.5)
os.system("clear")
Where text is the text you want to type, and time.sleep(XXX) is the time between words shown. 其中text是您要键入的文本,time.sleep(XXX)是显示的单词之间的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.