Create a message corresponding to localization with python translation string

Create a message corresponding to localization with python translation string

You may want to sort out error messages depending on the locale. I didn't know what to do in such a case, so I looked it up.

translationstring

Use translationstring. This seems to be used for localization in the package related to the pylons project. It seems that it uses the gettext mechanism that is often used for general translation.

python side code

"Failure" in Japanese locale. Otherwise, consider a string that displays "failure".

It seems that the function generated by translationstring.TranslationStringFactory should be used for the notation. Wrap it in a Translator Object to convert the value.

In addition to the code below, you need a .mo file in place.

translationstring_example.py

# -*- coding:utf-8 -*-
import gettext
import translationstring

# .To work well with the po file generation tool_It is better to name it
_ = translationstring.TranslationStringFactory('sample')

lang = gettext.translation("sample", "./locale", languages=["ja"], codeset="utf8")
translator = translationstring.Translator(lang)

print(translator(_("failure")))

Generate .mo file

The .mo file is the format used by gettext. Generated from a .po file using commands using msgfmt. Generate a .po file before the .mo file. Use pot-create for this.

lingua install

A package called lingua will generate a .po file for you. ligua itself doesn't need babel, but babel was requested when trying to run pot-create.

pip install lingua babel

Generate .po file

After installing lingua, you can use pot-create. Generate a .po file in place

mkdir -p locale/ja/LC_MESSAGES/
pot-create translation_example.py -o locale/ja/LC_MESSAGES/sample.po

The file name to rewrite the generated sample.po should be the same as the domain name passed to TranslationStringFactory.

Rewrite as follows. Originally, it is better to rewrite the part such as the translator's name. This time I just rewrote the last part

# 
# SOME DESCRIPTIVE TITLE
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2014.
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE 1.0\n"
"POT-Creation-Date: 2014-06-12 15:37+09:00\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS\n"
"Language-Team: LANGUAGE <[email protected]>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: \n"

#: ./translation_example.py:11
#, c-format
msgid "failure"
msgstr "Failure value"

The difference is as follows

diff --git a/locale/ja/LC_MESSAGES/sample.po b/locale/ja/LC_MESSAGES/sample.po
index 2559ffb..db040c4 100644
--- a/locale/ja/LC_MESSAGES/sample.po
+++ b/locale/ja/LC_MESSAGES/sample.po
@@ -18,4 +18,4 @@ msgstr ""
 #: ./translation_example.py:11
 #, c-format
 msgid "failure"
-msgstr ""
+msgstr "Failure value"

Creating a .mo file

Use msgfmt to create .mo files.

msgfmt locale/ja/LC_MESSAGES/sample.po -o locale/ja/LC_MESSAGES/sample.mo

$ tree
.
├── locale
│   └── ja
│       └── LC_MESSAGES
│           ├── sample.mo
│           └── sample.po
├── requirements.txt
└── translation_example.py

3 directories, 4 files

This will translate "failure" into "failure value" and display it.

$ python translation_example.py
Failure value

About the location of ja / LC_MESSAGES / sample.mo

gettext looks at the locales information and asks for the mapping to use when translating.

LANG="ja_JP.UTF-8"
LC_COLLATE="ja_JP.UTF-8"
LC_CTYPE="ja_JP.UTF-8"
LC_MESSAGES="ja_JP.UTF-8"
LC_MONETARY="ja_JP.UTF-8"
LC_NUMERIC="ja_JP.UTF-8"
LC_TIME="ja_JP.UTF-8"
LC_ALL=

It seems good to use gettext.find to check if the .mo file can be read successfully.

# -*- coding:utf-8 -*-
import gettext
print(gettext.find("sample", "./locale",["ja"]))
# ./locale/ja/LC_MESSAGES/sample.mo

You can find out where to create the .po file by looking at the gettext.find code.

gettext.py

# Locate a .mo file using the gettext strategy
def find(domain, localedir=None, languages=None, all=False):
    # Get some reasonable defaults for arguments that were not supplied
    if localedir is None:
        localedir = _default_localedir
    if languages is None:
        languages = []
        for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
            val = os.environ.get(envar)
            if val:
                languages = val.split(':')
                break
        if 'C' not in languages:
            languages.append('C')
    # now normalize and expand the languages
    nelangs = []
    for lang in languages:
        for nelang in _expand_lang(lang):
            if nelang not in nelangs:
                nelangs.append(nelang)
    # select a language
    if all:
        result = []
    else:
        result = None
    for lang in nelangs:
        if lang == 'C':
            break
        mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
        if os.path.exists(mofile):
            if all:
                result.append(mofile)
            else:
                return mofile
    return result

Roughly, get languages such as "ja" from ('LANGUAGE','LC_ALL','LC_MESSAGES','LANG'), You can see that it is trying to retrieve the value from the .mo file under localedir / ja / LC_MESSAGS /.

About translating strings that take arguments

translationstring can also translate sentences that take arguments.

msg2 = _("add-number", default="Add ${number}", mapping={"number": 1})

lang = gettext.translation("sample", "./locale", languages=["ja"], codeset="utf8")
translator = translationstring.Translator()

print(translator(_("add-number", mapping={"number": 10})))
#Add 10

At this time, write the .placeholder in $ {} in the .po file as shown below.

msgid "add-number"
msgstr "${number}Please add"

Recommended Posts

Create a message corresponding to localization with python translation string
Send a message to LINE with Python (LINE Notify)
Steps to create a Twitter bot with python
Create a directory with python
How to convert / restore a string with [] in python
[Python] How to create a 2D histogram with Matplotlib
How to install NPI + send a message to line with python
Create folders from '01' to '12' with python
Create a Mastodon bot with a function to automatically reply with Python
Probably the easiest way to create a pdf with Python3
Create a virtual environment with Python!
Post a message to Google Hangouts Chat with a thread (Python)
5 Ways to Create a Python Chatbot
Create a random string in Python
Convert to a string while outputting standard output with Python subprocess
[Introduction to Python] How to split a character string with the split function
Try to create a python environment with Visual Studio Code & WSL
Try to extract a character string from an image with Python3
I tried to create a list of prime numbers with python
How to create a heatmap with an arbitrary domain in Python
Python vba to create a date string for creating a file name
Create a Python function decorator with Class
Build a blockchain with Python ① Create a class
Send a message from Python to Slack
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
[Python] How to invert a character string
Create a word frequency counter with Python 3.4
[Cloudian # 3] Try to create a new object storage bucket with Python (boto3)
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
Create a tool to automatically furigana with html using Mecab from Python3
Steps to create a Python virtual environment with VS Code on Windows
A memo corresponding to Django's runserver moss in Python 2.7.11 entered with Homebrew
[Introduction to Python] How to write a character string with the format function
[Outlook] I tried to automatically create a daily report email with Python
3. Natural language processing with Python 1-2. How to create a corpus: Aozora Bunko
Send a message from Slack to a Python server
Create a frame with transparent background with tkinter [Python]
Edit Excel from Python to create a PivotTable
How to read a CSV file with Python 2/3
How to send a message to LINE with curl
How to create a Python virtual environment (venv)
How to embed a variable in a python string
How to create a function object from a string
Try to draw a life curve with python
Create a virtual environment with conda in Python
[Note] Create a one-line timezone class with python
You can easily create a GUI with Python
Create a python3 build environment with Sublime Text3
Try to make a "cryptanalysis" cipher with Python
Create a color bar with Python + Qt (PySide)
Decide to assign a laboratory with Python (fiction)
Python Note: When assigning a value to a string
Create a decision tree from 0 with Python (1. Overview)
Create a color-specified widget with Python + Qt (PySide)
Try to make a dihedral group with Python
How to create a multi-platform app with kivy
Create a Photoshop format file (.psd) with python
Create a Python console application easily with Click
Decrypt a string encrypted on iOS with Python
I want to write to a file with Python