使用streamlit.write(df)时文本被截断的问题求助
解决Streamlit中DataFrame长文本截断问题
当使用st.write(df)展示DataFrame时,长文本会被截断且手动添加换行无效,以下是几种可行的解决方法:
方法1:用st.dataframe()替代并配置列属性
st.dataframe()支持更精细的列配置,能直接开启文本自动换行并设置列宽:
import pandas as pd import streamlit as st df = pd.DataFrame({ 'col1': [1, 2, 3], 'col2': [ 'This is some text large text that will not be completely displayed, need to add break lines or something.', 'short text', 'another piece of text.' ] }) # 针对长文本列开启自动换行 st.dataframe( df, column_config={ "col2": st.column_config.TextColumn( "Long Text Column", width="medium", # 可选small/medium/large或具体像素值 wrap_text=True # 核心:开启文本换行 ) }, use_container_width=True # 让表格适配容器宽度 )
方法2:预处理文本插入HTML换行符(适配st.write())
如果必须用st.write(),可以在长文本中插入<br>标签,再通过允许HTML渲染实现换行(注意:仅在文本可信时使用,避免XSS风险):
import pandas as pd import streamlit as st # 自定义函数:按指定长度拆分文本并插入<br> def split_text_to_breaks(text, max_char_per_line=30): chunks = [] current_chunk = [] current_length = 0 for word in text.split(): if current_length + len(word) + 1 > max_char_per_line: chunks.append(' '.join(current_chunk)) current_chunk = [word] current_length = len(word) else: current_chunk.append(word) current_length += len(word) + 1 chunks.append(' '.join(current_chunk)) return '<br>'.join(chunks) df = pd.DataFrame({ 'col1': [1, 2, 3], 'col2': [ 'This is some text large text that will not be completely displayed, need to add break lines or something.', 'short text', 'another piece of text.' ] }) # 对长文本列应用换行处理 df['col2'] = df['col2'].apply(split_text_to_breaks) # 渲染HTML格式的表格 st.write(df.to_html(escape=False), unsafe_allow_html=True)
方法3:注入自定义CSS强制全局换行
通过自定义CSS让所有表格单元格文本自动换行,适合需要全局生效的场景:
import pandas as pd import streamlit as st # 注入CSS样式 st.markdown(""" <style> .dataframe tbody tr td { white-space: pre-wrap !important; word-wrap: break-word !important; } </style> """, unsafe_allow_html=True) df = pd.DataFrame({ 'col1': [1, 2, 3], 'col2': [ 'This is some text large text that will not be completely displayed, need to add break lines or something.', 'short text', 'another piece of text.' ] }) st.write(df)
内容的提问来源于stack exchange,提问作者Matias Navarrete
相关产品推荐
相关产品推荐

