2013-03-22 63 views
4

这是我的第一个python程序和我的第一个问题关于堆栈溢出,所以我道歉如果我的代码是一团糟,或者如果我的问题格式不正确。Python输出复杂的行与浮点数着色

我想打印同一行我已经打印,但每个浮动应根据其值不同的颜色。 (具体来说>.7是绿色的,.7<是红色的)什么是最好的方法来做到这一点?

oreName=[#string names] 

#escape char? I know there has to be a better way than this 
#but this is the best ive come up with as the escape char didnt 
#work the way I thought it should for '%' 
char = '%' 

netProfitBroker=[ 
[0,0,0,0,0,0,0,0,0,0], 
[0,0,0,0,0,0,0,0,0,0], 
[0,0,0,0,0,0,0,0,0,0]] 

##code that populates netProfitBroker 

def printOutput(array): 
    "this prints all of the lines" 
    for i in range(0,10): 
    print oreName[i]+"= %.3f \t 5"%(array[0][i])+char+"=%.3f \t10"%(array[1][i])+char+"=%.3f"%(array[2][i])  


print "\nnet profit brokered" 
printOutput(netProfitBroker) 

输出看起来有点像这样:(我失去了一些/我所有的空格的格式,当我在这里复制输出)

net profit brokered 

Veldspar = 0.234  5%=0.340 10%=-0.017 
Scordite = 0.752  5%=0.297 10%=0.259 
Pyroxeres = 0.406  5%=1.612 10%=2.483 
Plagioclase= 1.078  5%=0.103 10%=1.780 
Omber  = -7.120 5%=5.416 10%=4.612 
Kernite = -10.822 5%=15.366 10%=6.626 
Jaspet  = 17.772 5%=49.278 10%=62.380 
Hemorphite = -35.431 5%=82.912 10%=141.027 
Gneiss  = 8.086  5%=-4638.549 10%=-3610.570 
Arkonor = 349.867 5%=-545.284 10%=-340.298 

主要有:

"ore name=" arrayVal1 "5%="arrayVal2 "10%="arrayVal3 

所有数组val应该打印出3个小数位。

+0

您可以使用[termcolor](https://pypi.python.org/pypi/termcolor)软件包。 – isedev 2013-03-22 21:55:10

+0

可能的重复http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python – isedev 2013-03-22 21:56:09

回答

12

您可以在打印开始时使用ASCII颜色代码来更改颜色,例如RED为'\033[91m',蓝色为'\033[94m'

e.g

if array[0][i] > 7: 
    print '\033[94m' + oreName[i]+"= %.3f \t 5"%(array[0][i]) 
elif array[0][i] < 7: 
    print '\033[91m' + oreName[i]+"= %.3f \t 5"%(array[0][i]) 

你可以阅读有关ASCII转义码here

编辑:添加了附加示例代码。

下面是一些常见的颜色,你可以使用一个列表:

Red = '\033[91m' 
Green = '\033[92m' 
Blue = '\033[94m' 
Cyan = '\033[96m' 
White = '\033[97m' 
Yellow = '\033[93m' 
Magenta = '\033[95m' 
Grey = '\033[90m' 
Black = '\033[90m' 
Default = '\033[99m' 

另外在注释中。您可以链接这些以在同一行上获取不同的颜色。

print '\033[91m' + 'Red' + "\033[99m" + 'Normal' + '\033[94m' + 'Blue 

你甚至可以做一个功能。

# Store a dictionary of colors. 
COLOR = { 
    'blue': '\033[94m', 
    'default': '\033[99m', 
    'grey': '\033[90m', 
    'yellow': '\033[93m', 
    'black': '\033[90m', 
    'cyan': '\033[96m', 
    'green': '\033[92m', 
    'magenta': '\033[95m', 
    'white': '\033[97m', 
    'red': '\033[91m' 
} 


def print_with_color(message, color='red'): 
    print(COLOR.get(color.lower(), COLOR['default']) + message) 


print_with_color('hello colorful world!', 'magenta') 
print_with_color('hello colorful world!', 'blue') 
+0

这recolors整个行。我希望能做的就是重新着色漂浮物。每条线有三个浮动,每个浮动需要自己的颜色。 – Slicedbread 2013-03-23 02:21:58

+2

您可以简单地将它们'print'\ 033 [91m'+'Red'+'\ 033 [99m'+'Normal'+ print'\ 033 [94m'+'Blue' – eandersson 2013-03-23 02:39:35