【问题标题】:multi language support in python scriptpython脚本中的多语言支持
【发布时间】:2014-01-22 00:12:07
【问题描述】:

我有一个 large python (2.7) 脚本,它从数据库中读取数据并生成 pdf 格式的图片。我的图片有标签等字符串...

现在我想为脚本添加多语言支持,这样我就可以通过将变量传递给脚本来生成不同语言的相同图片。

我正在考虑开设一个包含所有字符串及其翻译在字典中的课程。例如:

Strings['string1'] = {'de':'string in german', 'en': 'string in english'}

我可以访问字符串

my_needed_string = 'string1'
selected_language = 'en'
Strings[my_needed_string][selected_language]

有没有更好、更专业的方法来做到这一点? “更好”是指更灵活且更易于维护?我至少有 80 种不同的字符串,使用 2 种或更多语言。

谢谢

【问题讨论】:

  • 你有多少个不同的字符串?如果是一些特定的字符串,那么它应该不是问题。否则看看 gettex。
  • 我会有至少 80 个字符串,也许我们会实现第三种语言
  • 在这种情况下,手动操作可能不是一个好主意...

标签: python string multilingual


【解决方案1】:

查看 python gettext 模块以获得 i18n 支持

【讨论】:

  • +1。对于这样一个简单的情况,gettext 可能就足够了。对于 not 的情况,您通常希望使用 babeli18n 等工具(搜索 PyPI),它们要么构建在 gettext 之上,要么模拟 gettext,所以它仍然是通常是一个很好的起点。
  • 我阅读了gettext 的文档,我认为它对我的需求来说太大了......也许我完全误解了它。
  • 嗯,这个想法很简单,你用英语编写所有字符串并用 _() 包装它们,然后你可以添加任意数量的语言,同时将额外的语言字符串保存在你之外的单独文件中源代码,我猜你比我们更了解你的需求,这只是一个建议......
【解决方案2】:

如果您只有几种语言,并且不想使用一些 i18n 的东西,请尝试以下其中一种:

示例(我只是在 py 文件中使用 dict,如果您想要专门的 json,请告诉我):

另外,这是用 python 3 而不是 2 编写的。

en.py

en = {
    "eng": "english",
    "heb": "hebrew",
    "menu": {
        "menu1": "one",
        "menu2": "two"
    }
}

he.py

he = {
    "eng": "אנגלית",
    "heb": "עברית",
    "menu": {
        "menu1": "אחד",
        "menu2": "שתיים"
    }
}

使用 SimpleNamespace 的选项 1:

from types import SimpleNamespace

#import language dicts from which ever folder and file they are, for me its the same folder and different files...
from .he import he
from .en import en

class NestedNamespace(SimpleNamespace):
    def __init__(self, dictionary, **kwargs):
        super().__init__(**kwargs)
        for key, value in dictionary.items():
            if isinstance(value, dict):
                self.__setattr__(key, NestedNamespace(value))
            else:
                self.__setattr__(key, value)

text = {}
text.update({"he": NestedNamespace(he)})
text.update({"en": NestedNamespace(en)})
print(text['he'].menu.menu1) #works

使用namedtuple的选项2(我认为这个比较慢,根据我读到的有关namedtuple的制作方式,但我不是专业人士,所以选择你喜欢的任何东西):

from collections import namedtuple

def customDictDecoder(dict1):
    for key, value in dict1.items():
        if type(value) is dict:
            dict1[key] = customDictDecoder(value)
    return namedtuple('X', dict1.keys())(*dict1.values())

text = {}
text.update({"he": customDictDecoder(he)})
text.update({"en": customDictDecoder(en)})
print(text['he'].menu.menu2) #works

如果你想让print(text.he.menu.menu1) 工作,这是可能的,但我看不出它的用途,如果你想要,请告诉我

【讨论】:

    【解决方案3】:

    我前段时间遇到过这个问题,只是通过用我需要的两种语言的单词创建两个数组来解决它。

    # array with english words
    engList = ["dog", "cat"]
    # array with german words
    gerList = ["Hund", "Katze"]
    

    然后我只是将另一个数组设置为所需的语言数组并使用该数组中的单词。

    # referenced array set to the english array
    langList = engList
    
    print(langList[0],"+",langList[1])
    
    # change to the german array when needed
    langList = gerList
    
    print(langList[0],"+",langList[1])
    

    当然,它远非完美,但它对我有用。 希望我能帮上忙!

    【讨论】:

      【解决方案4】:

      如果您只是制作一个不同的 .py 并在那里使用每种语言的 if 语句创建一个新类,则可能是一种更“pythonic 方式”:

      class Locale:
      def __init__(self, loc):
          if loc == "en":
              self.string = "something in English"
          elif loc == "fr":
              self.string = "something in French"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-08
        • 2011-01-04
        • 2010-12-29
        • 2011-07-22
        • 2011-02-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多