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

Python中text.properties的替代方案:实现字符串分离支持国际化

实现Python脚本读取独立properties文件的方案

嘿,这问题我熟!要把字符串迁移到独立的.properties文件,让Python脚本读取它来支持国际化,其实有两种简单靠谱的方式,完全贴合你的需求,我给你一步步拆解:

方式一:用Python标准库configparser

这个方法依赖Python自带的标准库,不需要额外安装包,不过需要给.properties文件加个小节(section):

  1. 调整你的text.properties文件,添加一个小节(比如[messages]):
[messages]
hello_statement=Hello world
  1. 修改hello_world.py,用configparser读取配置:
import configparser

# 初始化配置解析器
config = configparser.ConfigParser()
# 读取properties文件
config.read('text.properties')

# 从指定小节中获取对应字符串
hello_statement = config.get('messages', 'hello_statement')
print(hello_statement)

方式二:自定义读取函数(完全贴合你给出的原始格式)

如果你不想修改.properties文件的格式,完全用你给出的key=value无小节的样式,可以自己写个轻量的读取函数,不需要依赖任何额外库:

  1. 保持你的text.properties不变:
hello_statement=Hello world
  1. 在hello_world.py中实现读取函数并使用:
def load_properties(file_path):
    props = {}
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            # 跳过空行和以#开头的注释行
            if not line or line.startswith('#'):
                continue
            # 只按第一个等号分割,避免value里包含等号的情况
            key, value = line.split('=', 1)
            props[key.strip()] = value.strip()
    return props

# 加载properties文件内容
text_props = load_properties('text.properties')
# 获取目标字符串
hello_statement = text_props['hello_statement']
print(hello_statement)

扩展:支持多语言国际化

如果要实现多语言版本,只需要创建对应语言的properties文件(比如text_zh.properties、text_en.properties),然后根据当前语言选择加载对应的文件即可:

# 假设当前语言为中文
current_language = 'zh'
text_props = load_properties(f'text_{current_language}.properties')
hello_statement = text_props['hello_statement']
print(hello_statement)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:40:49