【问题标题】:Writing text to terminal with some period用一段时间将文本写入终端
【发布时间】:2021-03-06 09:22:21
【问题描述】:

我是 python 和编程的新手。当我试图获得经验时,我认为我可以制作一个终端谜语游戏。这将是一个简单的问答游戏。

我的方法如下: 有一个 .txt(包含谜语)文件,我用 python 程序打开它。我想模仿在终端上打字,所以我在很大程度上使用了时间模块。现在,我已经设法模仿在终端中打字,它以一种速度输入字母,没有暂停,但在某些地方我希望程序等待 2 或 4 秒才能继续输入(以获得更戏剧性的效果)。

我能够找到的一个解决方案是我在 .txt 文件中放置了符号(例如,“p-2”表示“暂停 2 秒”)。文本文件如下所示:

What is Lorem Ipsum?
p-1
Lorem Ipsum is simply a dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,
but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets
containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
p-2

Python 文件如下所示:

def text_output(message):
    for i in message:
        time.sleep(0.05)
        print(i, end='', flush=True)

if "p-1" in data:
    data = data.replace("p-1", "time.sleep(1)")

if "p-2" in data:
    data = data.replace("p-2", "time.sleep(2)")

if "p-4" in data:
    data = data.replace("p-4", "time.sleep(4)")

exec(data)

如您所见,代码在文本中查找符号并将其替换为 python 代码,然后 exec() 函数执行此代码。不过我不喜欢这种方式,我觉得有更方便的方式可以达到这种效果。

我们将非常感谢您的帮助。

【问题讨论】:

  • 如果我的回答解决了您的问题,您能接受吗?

标签: python python-3.x terminal


【解决方案1】:

我认为这是一个非常有趣的功能。这就是我要在每一行、每一个单词、每一个字符之后生成合理的输出......

import time
import random
with open("/path/to/file.txt", "r") as file:
    lines = file.readlines()

def text_output(message, t):
    for i in message:
        time.sleep(t)
        print(i, end='', flush=True)

for num, line in enumerate(lines):
    if num == 1:
        time.sleep(random.randrange(4, 5))      # after title
    for word in line.split(" "):
        time.sleep(random.randrange(0.5, 2))    # after a word
        for character in word:
            text_output(character, random.randrange(0.05, 0.5))     # after a character

【讨论】:

  • @nodargelovani 如果它解决了您的问题,请您接受我的回答吗?
  • 嘿。对不起,迟到的答案。您的方法真的很有趣,但是,它并不能解决我的问题。感谢您的关注!
猜你喜欢
  • 2021-07-28
  • 1970-01-01
  • 2012-05-09
  • 2014-09-16
  • 2019-09-28
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多