在 Python 中打印一个动态的大列表
Posted
技术标签:
【中文标题】在 Python 中打印一个动态的大列表【英文标题】:Printing a dynamic and large list in Python 【发布时间】:2018-01-11 17:15:21 【问题描述】:我正在尝试打印一个大型列表,例如一系列租船人或电视中的字幕。我附上了以下照片以了解更多信息:
如您所见,输入文本应从右向左旋转。
为了达到这一点,我编写了以下代码:
from __future__ import print_function
import os
from time import sleep
text = """A company which supplied lingerie to the Queen has lost its royal warrant over a book which revealed details of royal bra fittings.Rigby & Peller,
a luxury underwear firm founded in London, had held the royal warrant since 1960. It was withdrawn after June Kenton, who fitted bras for the Quee
n, released a book called 'Storm in a D-Cup'.Mrs Kenton said there was "nothing" in the book to "be upset about", adding that it was an "unbelieva
ble" decision.Buckingham Palace said it did not comment on individual companies"""
whole_Str = []
i = 0
while(i < len(text)):
rest = text[i:i+50]
i+=1
whole_Str.append(rest)
for sequence in whole_Str:
print (sequence, end ='\r')
sleep(0.1)
但是,有两个问题:
首先,python 编辑器不允许我在同一个地方重写此文本的不同部分。
第二个也是最重要的,我猜sleep()
不是造成延迟的合理解决方案,因为对于大型文本,系统不应停止仅打印字幕。
任何形式的帮助将不胜感激
【问题讨论】:
澄清一下,你想把它打印到终端窗口吗? 从右到左旋转是不是像水平滚动文字一样?sleep
不会停止系统,这通常意味着当前进程在这段时间内失去了 CPU 分配。
【参考方案1】:
也许你的第一个问题可以这样解决:
import sys
from time import sleep
text = """dummy text"""
whole_Str = text
for i in range(len(text)-50):
sys.stdout.write("\r" + text[i:i+50])
sys.stdout.flush()
sleep(0.1)
不知道你说的第二个是什么意思。
【讨论】:
【参考方案2】:我能够让它与 curses 库一起工作。代码看起来像这样。
import time
import curses
text = """A company which supplied lingerie to the Queen has lost its royal warrant over a book which revealed details of royal bra fittings.Rigby & Peller,
a luxury underwear firm founded in London, had held the royal warrant since 1960. It was withdrawn after June Kenton, who fitted bras for the Quee
n, released a book called 'Storm in a D-Cup'.Mrs Kenton said there was "nothing" in the book to "be upset about", adding that it was an "unbelieva
ble" decision.Buckingham Palace said it did not comment on individual companies"""
def pbar(window):
for i in text:
#add a character to the string
window.addstr(i)
#refresh the window so the new character appears
window.refresh()
#sleep to get the scroll effect
time.sleep(0.5)
#start the printing
curses.wrapper(pbar)
这是从左到右滚动的水平滚动文本的效果。
【讨论】:
以上是关于在 Python 中打印一个动态的大列表的主要内容,如果未能解决你的问题,请参考以下文章