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

如何在Streamlit仪表板中实现葡萄牙语数字格式显示?

在Streamlit中适配葡萄牙语数字格式的方案

一、使用Python内置locale模块(无需额外安装)

Python自带的locale模块可直接设置葡萄牙语区域,自动适配数字的千位/小数分隔符规则。

操作步骤与示例:

  1. 加载并指定葡萄牙语区域(支持巴西葡萄牙语pt_BR或欧洲葡萄牙语pt_PT)
  2. 用locale.format_string()格式化普通数字,locale.currency()处理货币格式
import streamlit as st
import locale

# 适配不同系统的区域设置
try:
    locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')
except:
    # Windows系统备选设置
    locale.setlocale(locale.LC_ALL, 'Portuguese_Brazil.1252')

num = 1000.5

# 格式化普通数字
formatted_num = locale.format_string("%.1f", num, grouping=True)
st.write(f"葡萄牙语格式数字:{formatted_num}")  # 输出 1.000,5

# 格式化巴西雷亚尔货币
formatted_currency = locale.currency(num, symbol=True, grouping=True)
st.write(f"葡萄牙语格式货币:{formatted_currency}")  # 输出 R$ 1.000,50

注意:部署到云平台(如Streamlit Cloud)时,需先安装对应语言包,可在启动脚本中添加sudo apt-get install -y language-pack-pt,或在requirements.txt中声明依赖。

二、Streamlit组件的直接适配

对于st.metric这类默认用英语格式的组件,直接传入格式化后的字符串即可:

import streamlit as st
import locale

locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')
num = 1000.5

st.metric(
    label="示例数值",
    value=locale.format_string("%.1f", num, grouping=True),
    delta=locale.format_string("%.1f", 200.75, grouping=True)
)

三、使用第三方库Babel(跨平台更灵活)

如果locale模块在部分环境下兼容性不佳,可使用专门处理国际化的Babel库:

  1. 先安装:pip install babel
  2. 示例代码:
import streamlit as st
from babel.numbers import format_number, format_currency

num = 1000.5

# 格式化普通数字
formatted_num = format_number(num, locale='pt_BR')
st.write(f"葡萄牙语格式数字:{formatted_num}")  # 输出 1.000,5

# 格式化货币
formatted_currency = format_currency(num, 'BRL', locale='pt_BR')
st.write(f"葡萄牙语格式货币:{formatted_currency}")  # 输出 R$ 1.000,50

四、自定义格式化函数(无依赖方案)

不想依赖任何库的话,可自行编写简单函数处理格式转换:

import streamlit as st

def format_portuguese_number(num, decimal_places=1):
    # 分割整数与小数部分
    integer_part, decimal_part = str(num).split('.')
    # 添加千位分隔符
    integer_part = '.'.join([integer_part[max(i-3, 0):i] for i in range(len(integer_part), 0, -3)][::-1])
    # 保留指定小数位数
    decimal_part = decimal_part[:decimal_places]
    return f"{integer_part},{decimal_part}"

num = 1000.5
st.write(f"葡萄牙语格式数字:{format_portuguese_number(num)}")  # 输出 1.000,5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 19:39:59