Python 3.6 sleep() 在同一个字符串中不同的睡眠时间取决于字符

Python 3.6 sleep() different sleep times within same string depending on character

在 python 3.6 中,我正在尝试打印一个字符串,其中字符之间有延迟,句子末尾的标点符号延迟更长,以伪模拟英语口语。这是我的代码。我的问题是我得到了字符之间的延迟,但我没有得到句子之间更长的延迟。

import time
import sys


def delay_print(s):
    for c in s:
        if c != "!" or "." or "?":
            sys.stdout.write(c)
            # If I comment out this flush, I get each line to print
            # with the longer delay, but I don't get a char-by char 
            # delay
            # for the rest of the sentence.
            sys.stdout.flush()
            time.sleep(0.05)
        elif c == "!" or "." or "?":
            sys.stdout.write(c)
            sys.stdout.flush()
            time.sleep(3)


delay_print( """
    Hello.
    I want this to have an added delay after sentence-ending 
    punctuation?
    But I also want it to have a shorter delay after each character 
    that isn't one of those chars.
    This is supposed to mimic speech patterns. Like if you've ever 
    played SNES Zelda: A Link to the Past.
    Why isn't this code doing what I want it to?.
    What I've written is broken and I don't know why!
""")

您的 or 子句没有按照您认为的那样进行。第一个检查这三件事中的任何一个是否为真:

  1. character != "!"
  2. bool(".")
  3. bool("?")

请注意,2 和 3 始终为真。

If 语句短路评估。如果输入的字符是 .,它会检查条件 1 并发现它为假。然后它将在评估 False or "." 中包含条件 2。由于 "." 始终为真,因此它短路并且 returns "." 的计算结果为真。自己试一下,在解释器中输入 False or ".",你会发现 returns ".".

就个人而言,我会用这样的集合实现来做到这一点:

if c not in {"!", ".", "?"}:

无论 c 的值是什么,您正在测试的两个条件的计算结果总是 True:

>>> letter == "!" or "." or "?"
'.'
>>> letter = "a"
>>> if letter != "!" or "." or "?":
    print("not punctuation")


not punctuation
>>> if letter == "!" or "." or "?":
    print("punctuation")


punctuation

正如另一位用户所建议的那样,将测试更改为:

对您来说可能更有意义
>>> letter in "!.?"
False
>>> letter not in "!.?"
True

此外,从更文体的角度来看,我会考虑在字母之间使用随机延迟,以使其更具有机感。

import random

...

delay = random.random() + 2.5
sleep(delay)

试一试!您的第一个 if 语句需要使用 'and' 而不是 'or',因为它始终为 True。

def delay_print(s):
    for c in s:
        if c != "!" and c != "." and c != "?":
            sys.stdout.write(c)
            sys.stdout.flush()
            time.sleep(0.05)
        else:
            sys.stdout.write(c)
            sys.stdout.flush()
            time.sleep(3)