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

js5cn81o  于 2023-02-06  发布在  Python
关注(0)|答案(3)|浏览(97)
    • 此问题在此处已有答案**:

Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?(8个答案)
三年前关闭了。
在python3.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!
""")
kfgdxczn

kfgdxczn1#

你的or子句没有做你认为它在做的事情。第一个子句检查以下三个条件中是否有一个为True:

  1. character != "!"
  2. bool(".")
  3. bool("?")
    请注意,2和3始终为真。
    If语句短路求值。如果字符输入是.,它将检查条件1并发现它为false。然后它将在求值False or "."中包含条件2。由于"."始终为true,因此它短路并返回求值为true的"."。自己尝试一下,在解释器中键入False or ".",你会发现它会返回"."
    就我个人而言,我会使用如下的set实现来完成此操作:
if c not in {"!", ".", "?"}:
vc9ivgsu

vc9ivgsu2#

无论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)
hmae6n7t

hmae6n7t3#

给予看!你的第一个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)

相关问题