gpt4 book ai didi

python - 无论如何,是否可以使用 PrettyTable 根据条件设置 元素的样式

转载 作者:行者123 更新时间:2023-12-01 08:22:33 24 4
gpt4 key购买 nike

代码如下:

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<0,则将change_1h、change_24h和change_7d设置为红色,如果change>0,则设置为绿色。使用 PrettyTable 可以做到这一点吗?

最佳答案

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

这就是您将得到的:

enter image description here

关于python - 无论如何,是否可以使用 PrettyTable 根据条件设置 <td> 元素的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54528569/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com