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

Streamlit st.write_stream不保留换行符问题求助

解决Streamlit st.write_stream保留换行符的问题

原代码的问题

  1. 使用了未定义的_LOREM_IPSUM变量,应替换为你定义好的response
  2. split()方法会将所有空白字符(包括换行符)统一替换为空格,直接丢失换行结构
  3. 调用st.write(stream_data)错误,需改为st.write_stream(stream_data())(传入生成器实例而非函数本身)

解决方案

方案1:按字符流式输出(完全保留原格式)

直接遍历文本的每个字符,包括换行符,实现最精准的格式还原:

import streamlit as st
import time

response = """
Here is a new recipe for Chicken Biryani using the ingredients provided:    

Chicken Dum Biryani  

Prep Time: 30 mins Cook Time: 30 mins Servings: 2  

Ingredients:

2 bone-in chicken thighs (about 1 lb total), skin removed
1 cup basmati rice, rinsed
1 small onion, finely chopped
2 garlic cloves, minced
1 tbsp ginger, minced
"""

def stream_data():
    for char in response:
        yield char
        time.sleep(0.05)  # 可根据需求调整打字速度

if st.button("Stream data"):
    st.write_stream(stream_data())

方案2:按单词输出(保留换行结构)

如果需要按单词停顿的效果,可以先按行拆分文本,处理每行单词后添加换行符:

import streamlit as st
import time

response = """
Here is a new recipe for Chicken Biryani using the ingredients provided:    

Chicken Dum Biryani  

Prep Time: 30 mins Cook Time: 30 mins Servings: 2  

Ingredients:

2 bone-in chicken thighs (about 1 lb total), skin removed
1 cup basmati rice, rinsed
1 small onion, finely chopped
2 garlic cloves, minced
1 tbsp ginger, minced
"""

def stream_data():
    lines = response.split('\n')
    for line in lines:
        words = line.split()
        for word in words:
            yield word + " "
            time.sleep(0.02)
        yield '\n'  # 每行结束后输出换行符
        time.sleep(0.1)  # 换行后停顿,提升阅读体验

if st.button("Stream data"):
    st.write_stream(stream_data())

效果说明

  • 方案1会完全复现原文本的所有格式,包括空行和换行,每个字符依次输出,模拟真实打字效果
  • 方案2保留段落结构,按单词输出,适合需要强调单词停顿的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 03:37:34