例如,我有一个文件,如下所示:
while True:
if test = 10:
print(a, b)
现在我写了一个脚本来读取该文件,然后......以随机颜色打印所有单词。这是我的代码:
color = [color for color in range(91, 97)]
with open(sys.argv[1], 'r') as f:
for i in f.readlines():
for w in i.split():
print('\033[{0}m{1}\033[{0};m'
.format(random.choice(color), w), end='')
print(' ', end='')
print()
确定,它正在发挥作用。但是.split()
并没有保存所有空格,所以输出没有缩进:
while True
if test = 10:
print(a, b)
现在我的问题是:如何节省空间?
答案 0 :(得分:2)
您可以根据' '
(空格,而不是None
按所有空格分割)进行拆分,只打印出包含除空白之外的任何内容的单词(为此,您只需检查如果w.strip()
是空字符串或不是。例子 -
import random
import sys
color = [color for color in range(91, 97)]
with open(sys.argv[1], 'r') as f:
for i in f:
for w in i.rstrip().split(' '):
if w.strip():
print('\033[{0}m{1}\033[{0};m'
.format(random.choice(color), w), end='')
print(' ', end='')
print()
演示 -
使用OP的代码 -
←[91mwhile←[91;m ←[92mTrue:←[92;m
←[96mif←[96;m ←[92mtest←[92;m ←[95m=←[95;m ←[95m10:←[95;m
←[92mprint(a,←[92;m ←[93mb)←[93;m
以上建议的更改 -
←[93mwhile←[93;m ←[93mTrue:←[93;m
←[94mif←[94;m ←[93mtest←[93;m ←[91m=←[91;m ←[94m10:←[94;m
←[91mprint(a,←[91;m ←[96mb)←[96;m