一、通过字典实现
python
import locale
# 定义中英文对照的字典
translation_dict = {
'account': {'en': 'Account', 'zh': '账号'},
'password': {'en': 'Password', 'zh': '密码'},
'logon': {'en': 'Logon', 'zh': '登录'}
# 其他需要翻译的内容...
}
def get_translation_dict():
"""根据系统语言选择对应的翻译"""
# language_code:获取系统语言 encoding:获取当前系统默认的文本编码格式
language_code, encoding = locale.getdefaultlocale()
if 'en' in language_code:
return {key: value['en'] for key, value in translation_dict.items()}
elif 'zh' in language_code:
return {key: value['zh'] for key, value in translation_dict.items()}
else:
# 如果系统语言不是中文或英文,则返回默认的语言字典
return {key: value['en'] for key, value in translation_dict.items()}
if __name__ == "__main__":
translation = get_translation_dict()
print(translation['account'])
二、通过 json 实现
首先,创建一个JSON文件(例如translation.json)来存储翻译内容。示例内容如下:
javascript
{
"en": {
"account": "Account",
"password": "Password",
"logon": "Logon"
},
"zh": {
"account": "账号",
"password": "密码",
"logon": "登录"
}
}
然后,使用Python的json模块读取JSON文件,并根据系统语言选择相应的翻译内容。示例代码如下:
python
import locale
import json
def get_translation_dict():
"""根据系统语言选择对应的翻译"""
language_code, _ = locale.getdefaultlocale()
with open('translation.json', 'r', encoding='utf-8') as file:
translations = json.load(file)
if 'en' in language_code:
return translations['en']
elif 'zh' in language_code:
return translations['zh']
else:
return translations['en']
if __name__ == "__main__":
translation = get_translation_dict()
print(translation['password'])
三、通过 ini 实现
首先,创建一个配置文件 translation.ini,内容如下:
python
[en]
account = Account
password = Password
logon = Logon
[zh]
account = 账号
password = 密码
logon = 登录
然后使用 Python 中的 ConfigParser 模块来读取配置文件,根据系统语言选择相应的翻译内容,示例代码如下:
python
import locale
import configparser
def get_translation_dict():
"""根据系统语言选择对应的翻译"""
language_code, _ = locale.getdefaultlocale()
config = configparser.ConfigParser()
config.read('translation.ini', encoding='utf-8')
if 'en' in language_code:
return dict(config['en'])
elif 'zh' in language_code:
return dict(config['zh'])
else:
return dict(config['en'])
if __name__ == "__main__":
translation = get_translation_dict()
print(translation['logon'])