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

如何在Python中为文本逐字符设置不同颜色?

Solution: Render Colored Text in Jupyter/IPython via HTML

Got it, let's tackle this step by step. You want to color each character based on its corresponding -1 to 1 score (red for -1, green for 1, transitional colors in between) and display it neatly in JupyterHub or IPython. Using HTML rendering is the most straightforward way to get readable, text-based colored output—here's how to make it work:

Step 1: Import Required Libraries

First, we'll need matplotlib for color mapping and IPython.display.HTML to render the colored text:

import matplotlib as mpl
import matplotlib.cm as cm
from IPython.display import HTML

Step 2: Parse Your Input Data

Your provided data has two arrays: one with characters, one with string-formatted values. Let's convert them into usable lists:

# Your input data
data = [
    ['a', 'c', 'm', 'e', 't', 'e', 'l', 'l', 'm', 'e'],
    ['0.1716490432811229', '0.062389299621661884', '0.26545182258229466', '-0.07999088246625552', '-0.4499291603930515', '-0.7465421931327068', '-0.812006046307664', '-0.8443500193245104', '-0.865253671942029','-0.8697487071105282']
]

chars = data[0]
# Convert string values to floats for color mapping
scores = [float(val) for val in data[1]]

Step 3: Generate Color Mapping

Use your existing color logic to get RGBA values for each score:

# Set up normalization (maps -1 to 1 to the colormap range)
norm = mpl.colors.Normalize(vmin=-1, vmax=1)
# Use RdYlGn for red → yellow → green transition (matches your 0 midpoint requirement)
cmap = cm.RdYlGn
mappable = cm.ScalarMappable(norm=norm, cmap=cmap)

# Get RGBA colors for each score
colors = mappable.to_rgba(scores)

Step 4: Build and Render Colored HTML Text

Wrap each character in a <span> tag with inline CSS for color, then display the result:

# Build the HTML string with styled characters
colored_text = ""
for char, color in zip(chars, colors):
    # Format RGBA values for CSS (decimals work directly)
    rgba_str = f"rgba({color[0]:.3f}, {color[1]:.3f}, {color[2]:.3f}, {color[3]:.3f})"
    # Adjust font-size here for better readability
    colored_text += f"<span style='font-size: 20px; color: {rgba_str};'>{char}</span>"

# Display the colored text in Jupyter/IPython
HTML(colored_text)

Quick Customization Tips

  • If you want a different midpoint color (like pure white instead of yellow), swap the colormap—try cm.RdBu_r (reverse red-blue) or create a custom colormap with mpl.colors.LinearSegmentedColormap.
  • Tweak the font-size value in the CSS to make the text larger or smaller based on your needs.

Alternative: Tabular Display with Pandas

If you want to pair each colored character with its score, use a styled pandas DataFrame:

import pandas as pd

df = pd.DataFrame({'Character': chars, 'Score': scores})

def style_char(row):
    color = mappable.to_rgba(row['Score'])
    rgba_str = f"rgba({color[0]:.3f}, {color[1]:.3f}, {color[2]:.3f}, {color[3]:.3f})"
    return [f'color: {rgba_str}; font-size: 20px;', '']

# Render the styled DataFrame
df.style.apply(style_char, axis=1)

This will show a table with colored characters alongside their numerical values, great for reference or debugging.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:31:09