You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何按冷暖色谱为字符串字符映射对应数值实现彩色打印

字符显著性热力着色实现方法

核心逻辑是将等长的权重数组归一化到0-1区间,再将每个位置的权重值映射到冷-暖渐变的色阶上,给对应字符着色即可,下面提供两种可直接运行的实现:


终端直接打印彩色字符

支持24位真彩色的终端可以直接通过ANSI转义码输出带颜色的字符,无需额外依赖:

import numpy as np

def print_colored_text(s: str, weight_arr: np.ndarray):
    # 权重归一化到0-1区间
    norm_weight = (weight_arr - weight_arr.min()) / (weight_arr.max() - weight_arr.min())
    output = ""
    for c, w in zip(s, norm_weight):
        # 0值对应冷色蓝,1值对应暖色红,线性插值计算RGB值
        r = int(255 * w)
        g = int(64 * (1 - abs(2*w - 1))) # 给中间值加少量绿色过渡,避免颜色太生硬
        b = int(255 * (1 - w))
        # 拼接ANSI真彩色转义序列
        output += f"\033[38;2;{r};{g};{b}m{c}\033[0m"
    print(output)

# 测试用例
s = 'abcdefghijklmnopqrstuvwxyz'
arr = np.linspace(0, 1, len(s))
print_colored_text(s, arr)

生成论文同款可视化图片

如果需要导出和参考效果一致的配图用于文档/论文,可以用matplotlib逐字符绘制,色阶匹配度更高:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors

def save_colored_text(s: str, weight_arr: np.ndarray, save_path="text_saliency.png", fontsize=24):
    norm = colors.Normalize(vmin=weight_arr.min(), vmax=weight_arr.max())
    # 选用蓝-红冷暖色阶,和原论文效果对齐
    cmap = plt.get_cmap("bwr")

    fig, ax = plt.subplots(figsize=(len(s)*0.35, 1.2))
    ax.set_axis_off()
    # 逐字符按对应权重着色绘制
    for idx, (char, w) in enumerate(zip(s, weight_arr)):
        ax.text(
            idx, 0.5, char, 
            fontsize=fontsize, 
            color=cmap(norm(w)),
            ha="center", va="center"
        )
    ax.set_xlim(-0.6, len(s)-0.4)
    ax.set_ylim(0, 1)
    plt.tight_layout()
    plt.savefig(save_path, dpi=200, bbox_inches="tight")
    plt.close()

# 测试用例
s = 'abcdefghijklmnopqrstuvwxyz'
arr = np.linspace(0, 1, len(s))
save_colored_text(s, arr)

提示:如果需要更贴近原论文的jet色阶(深蓝-青-黄-红渐变),只需要把代码里的cmap = plt.get_cmap("bwr")替换为cmap = plt.get_cmap("jet")即可。


内容的提问来源于stack exchange,提问作者noyk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.31 00:01:18