【问题标题】:Remove and replace printed words in same command line在同一命令行中删除和替换打印的单词
【发布时间】:2021-08-28 19:28:15
【问题描述】:

我想编写一个函数,让用户给出文件名并设置“速度”参数以以所需的速度显示单词。然后该函数开始在文件中逐字打印,但在同一命令行上替换前一个。

这是我的功能:

def quick_reader(a):
    fhandle = open(a)
    document = fhandle
    for line in document:
        words = line.split()
        for i in range(0,len(words)):
            print("> " + words[i], end="\r")
            time.sleep(1)

问题是到第三个单词时,它开始为某些单词添加额外的字母并将其弄乱。它确实打印在同一行并替换了前一个单词,只是弄乱了单词。

【问题讨论】:

    标签: python string format


    【解决方案1】:

    它搞砸了,因为您需要“擦除”之前 print 中的超调字符。

    这样做的一种方法是存储前一行的长度,然后在下一次迭代时打印尽可能多的空格,然后再打印下一行。

    def quick_reader(a, prefix="> ", delay=1):
        lgth = 0
        pref_length = len(prefix)
        with open(a) as fhandle:
            document = fhandle
            line = fhandle.readline()
            while line:
                # Strip() after the while check,
                # so it doesn't exit the loop with an empty line.
                line = line.strip()
                # Erasing the line
                print(" " * lgth , end="\r")
                # Printing the new line
                print(prefix + line, end="\r")
                # Storing the current line's length
                lgth  = len(line) + pref_length
                time.sleep(delay)
                line = fhandle.readline()
    

    【讨论】:

      【解决方案2】:

      我之前(现已删除)的评论不正确,输出退格不会删除字符。相反,您需要用空格覆盖该行以摆脱它们:

      import time
      
      def quick_reader(filepath, delay=1):
          with open(filepath) as file:
              for line in file:
                  for word in line.split():
                      print('>', word, end='', flush=True)
                      time.sleep(delay)
                      print('\r ', ' ' * len(word),  end='\r', flush=True)
          print()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        • 2020-07-29
        • 1970-01-01
        • 2015-07-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多