Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7逐字延时_Python - Fatal编程技术网

Python 2.7逐字延时

Python 2.7逐字延时,python,Python,通过将字符串设置为列表,然后在迭代中打印每个单词时添加空格,可以使您的生活更轻松。像这样: 迭代单词时,只需使用split将其列为一个列表。然后在stdout中写入,只需在每个单词后添加空格即可 对代码所做的修改。这应该起作用: import sys import time from random import randrange words = ''' this is a cool delay typing program, right now it print string by stri

通过将字符串设置为列表,然后在迭代中打印每个单词时添加空格,可以使您的生活更轻松。像这样:

迭代单词时,只需使用
split
将其列为一个列表。然后在
stdout中写入
,只需在每个单词后添加空格即可

对代码所做的修改。这应该起作用:

import sys
import time
from random import randrange

words = ''' this is a cool delay typing program,
right now it print string by string.

I need to know how to make it print a word by word.'''

for i in words:
    sys.stdout.write(i)
    sys.stdout.flush()
    seconds = ".8" + str(randrange(1,5,2))
    seconds = float(seconds)
    time.sleep(seconds)

idjaw答案中的代码是实现这一点的直接方法,但它将每个空格序列转换为单个空格。我的代码保留了原始的空白字符,也就是说,源字符串中多个空格的任何序列都按原样打印,以及诸如换行符和制表符之类的内容

使用标准的
str
方法适当地分割源字符串有点混乱,因此我使用了模块


我删除了随机内容:我认为添加1或3百分之一秒的随机延迟没有多大意义。

我没有看到它打印任何内容。是的,我只是重新检查它。它会延迟0.8秒。更准确的说法是,您的程序逐字符打印,因为字符串可以是任何长度(包括零)。谢谢。。。我该如何结束这个问题?@JJse不知道。我以前从未问过任何问题P@JJse当前位置没有必要关闭此问题。。。其他人可能希望提供新的答案但是通过接受一个答案,你已经表明你的问题已经得到了满意的回答,因此不太可能吸引更多的答案。
import sys
import time
from random import randrange

words = ''' this is a cool delay typing program,
right now it print string by string.

I need to know how to make it print a word by word.'''

for i in words.split():
    sys.stdout.write("{} ".format(i))
    sys.stdout.flush()

    seconds = ".8" + str(randrange(1,5,2))
    seconds = float(seconds)
    time.sleep(seconds)
import sys
from time import sleep
import re

words = ''' This is a cool delay typing program.
It used to print character by character...

But now it prints word by word. '''    

def delay_typer(words, delay=0.8, stream=sys.stdout):
    tokens = re.findall(r'\s*\S+\s*', words)
    for s in tokens:
        stream.write(s)
        stream.flush()
        sleep(delay)

delay_typer(words)
delay_typer('I hope\nyou\tlike it. :)\n', 0.2)