Post

i18n

i18n

i18n

简介

国际化(Internationalization,简称 i18n)是指设计和开发软件应用时,使其能够适应不同语言、地区和文化的过程。i18n 的目标是让软件能够在不进行代码修改的情况下,支持多种语言和地区的用户。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import json

zh = {'hello': '你好', 'world': '世界', 'greeting': '你好,{name}!'}
en = {'hello': 'Hello', 'world': 'World', 'greeting': 'Hello, {name}!'}
fr = {'hello': 'Bonjour', 'world': 'Monde', 'greeting': 'Bonjour, {name}!'}
de = {'hello': 'Hallo', 'world': 'Welt', 'greeting': 'Hallo, {name}!'}

with open('locales.json', 'w', encoding='utf-8') as f:
    json.dump({'zh': zh, 'en': en, 'fr': fr, 'de': de}, f, ensure_ascii=False, indent=4)

class i18n:
    def __init__(self, locale='en'):
        with open('locales.json', 'r', encoding='utf-8') as f:
            self.locales = json.load(f)
        self.set_locale(locale)

    def set_locale(self, locale):
        if locale in self.locales:
            self.current_locale = locale
        else:
            raise ValueError(f"Locale '{locale}' not supported.")

    def __repr__(self):
        return f"<i18n current_locale='{self.current_locale}'>"

    def __call__(self, key):
        return self.locales[self.current_locale].get(key, key)

i18n_instance = i18n(locale='zh')
print(i18n_instance('hello'))  # Output: 你好
print(i18n_instance('greeting').format(name='Alice'))  # Output: 你好,Alice!
print(i18n_instance)  # Output: <i18n current_locale='zh'>

This post is licensed under CC BY 4.0 by the author.