这是代码:
from prettytable import PrettyTable
import requests
def market_table():
api = "https://api.coinmarketcap.com/v2/ticker/"
raw_data = requests.get(api).json()
data = raw_data['data']
table = PrettyTable()
for currency in data:
name = data[currency]['name']
market_cap = data[currency]['quotes']['USD']['market_cap']
price = data[currency]['quotes']['USD']['price']
change_1h = data[currency]['quotes']['USD']['percent_change_1h']
change_24h = data[currency]['quotes']['USD']['percent_change_24h']
change_7d = data[currency]['quotes']['USD']['percent_change_7d']
table.add_row([name,market_cap,price,change_1h,change_24h,change_7d])
table.field_names = ["Name","Market Cap","Price","Change 1h","Change 24h","Change 7d"]
table.sortby = "Market Cap"
table.reversesort = True
market_table = table.get_html_string()
return market_table
我想做的是将change_1h,change_24h和change_7d的样式设置为在change <0时为红色,而在change> 0时为绿色。使用PrettyTable有可能吗?
答案 0 :(得分:1)
PrettyPrint无法进行颜色修改,但是您可以应用自己的后处理:
import re
import requests
from prettytable import PrettyTable
def market_table():
changes = []
data = requests.get('https://api.coinmarketcap.com/v2/ticker').json()['data']
table = PrettyTable(['Name', 'Market Cap', 'Price', 'Change 1h', 'Change 24h', 'Change 7d'], sortby='Market Cap', reversesort=True)
for currency in data:
change_1h = data[currency]['quotes']['USD']['percent_change_1h']
change_24h = data[currency]['quotes']['USD']['percent_change_24h']
change_7d = data[currency]['quotes']['USD']['percent_change_7d']
changes.extend([change_1h, change_24h, change_7d])
table.add_row([data[currency]['name'], data[currency]['quotes']['USD']['market_cap'],
data[currency]['quotes']['USD']['price'], change_1h, change_24h, change_7d])
html = table.get_html_string()
for change in changes:
color = '#00FF00' if change > 0 else '#FF0000'
html = re.sub('<td>{}</td>'.format(change), '<td bgcolor="{}">{}</td>'.format(color, change), html)
return html
这是您将得到的: