有没有根据使用 PrettyTable 的条件来设置 <td> 元素的样式

Is there anyway to style <td> elements based on a conditional using PrettyTable

代码如下:

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 设置为红色(如果变化<0),如果变化>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

这就是您将获得的: