Python中text.properties的替代方案:实现字符串分离支持国际化
实现Python脚本读取独立properties文件的方案
嘿,这问题我熟!要把字符串迁移到独立的.properties文件,让Python脚本读取它来支持国际化,其实有两种简单靠谱的方式,完全贴合你的需求,我给你一步步拆解:
方式一:用Python标准库configparser
这个方法依赖Python自带的标准库,不需要额外安装包,不过需要给.properties文件加个小节(section):
- 调整你的
text.properties文件,添加一个小节(比如[messages]):
[messages] hello_statement=Hello world
- 修改
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无小节的样式,可以自己写个轻量的读取函数,不需要依赖任何额外库:
- 保持你的
text.properties不变:
hello_statement=Hello world
- 在
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
相关产品推荐
相关产品推荐

