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

如何在Streamlit中正确显示文本?当前出现格式异常问题

解决Streamlit文本格式混乱的方案

1. 先清理原始文本中的冗余内容

如果你的response2混杂了未闭合HTML标签、转义字符或多余换行,先做预处理:

import re

# 移除所有HTML标签
cleaned_text = re.sub(r'<[^>]*>', '', response2)
# 替换转义字符为正常字符
cleaned_text = cleaned_text.replace('&lt;', '<').replace('&gt;', '>').replace('&amp;', '&')
# 规整换行:保留段落级分隔,去除多余空行
cleaned_text = re.sub(r'\n\s*\n', '\n\n', cleaned_text).strip()

st.markdown(cleaned_text)

2. 强制纯文本渲染

如果不需要解析Markdown格式,直接用st.text(),它会原样展示文本,不会处理任何格式:

st.text(response2)

3. 调整st.markdown的使用方式

  • 如果response2是Markdown格式但混杂少量HTML,不要加unsafe_allow_html=True,这个参数会让Streamlit优先解析HTML,反而破坏Markdown格式;
  • 如果是纯文本带手动换行,st.text()比st.write()更适配,后者会自动合并多余换行。

4. 换用更严格的格式转换库

如果markdown2效果不佳,试试mistune做格式转换:

import mistune

# 将Markdown转为纯文本
renderer = mistune.create_markdown(renderer='text')
plain_text = renderer(response2)
st.write(plain_text)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:12:07