【问题标题】:How can I use gettext in jupyter-notebook/python interactive mode?如何在 jupyter-notebook/python 交互模式下使用 gettext?
【发布时间】:2017-11-16 01:48:03
【问题描述】:

我使用从this question 获得的以下代码从他们的俄罗斯名称中获取国家代码。

def get_country_code(russian_name):
    gettext.translation('iso3166', pycountry.LOCALES_DIR, languages=['RU']).install()
    country_code = ''.join([country.alpha_2 for country in pycountry.countries if _(country.name) == russian_name])
    return country_code

但是当我尝试在我的 jupyter-notebook 中使用这个功能时,它给了我以下错误:

TypeError: 'str' object is not callable

这似乎是因为在 jupyter 以及交互模式下 _ 表示先前计算的结果,但 gettext 将其定义为它的函数。

如何在 Jupyter 中执行此代码?

【问题讨论】:

    标签: python ipython jupyter-notebook jupyter gettext


    【解决方案1】:

    我找到了问题的解决方案。 install() 函数在内置函数中设置变量 _,如下所示:

    builtins.__dict__['_'] = self.gettext
    

    所以我们可以改用这个函数。

    def get_country_code(russian_name):
        rus = gettext.translation('iso3166', pycountry.LOCALES_DIR, languages=['RU'])
        rus.install()
        country_code = ''.join([country.alpha_2 for country in pycountry.countries if rus.gettext(country.name) == russian_name]) # u'FR'
        return country_code
    

    【讨论】:

      猜你喜欢
      • 2018-05-11
      • 2019-11-14
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 2022-08-18
      • 2016-02-24
      • 2021-02-17
      • 2016-11-16
      相关资源
      最近更新 更多