<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Archives des tradution - La programmation sur le web</title>
	<atom:link href="https://programmation.surleweb-france.fr/tag/tradution/feed/" rel="self" type="application/rss+xml" />
	<link>https://programmation.surleweb-france.fr/tag/tradution/</link>
	<description>La programmation gratuite pour tous</description>
	<lastBuildDate>Sat, 08 May 2021 09:32:25 +0000</lastBuildDate>
	<language>fr-FR</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://i0.wp.com/programmation.surleweb-france.fr/wp-content/uploads/2023/08/cropped-19518430-icone-de-programmation-pour-votre-site-web-mobile-presentation-et-conception-de-logo-gratuit-vectoriel.jpg?fit=32%2C32&#038;ssl=1</url>
	<title>Archives des tradution - La programmation sur le web</title>
	<link>https://programmation.surleweb-france.fr/tag/tradution/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">176210735</site>	<item>
		<title>Python, créer des traductions pour son application</title>
		<link>https://programmation.surleweb-france.fr/python-creer-des-traductions-pour-son-application/</link>
					<comments>https://programmation.surleweb-france.fr/python-creer-des-traductions-pour-son-application/#respond</comments>
		
		<dc:creator><![CDATA[Zigomato]]></dc:creator>
		<pubDate>Sat, 08 May 2021 09:32:22 +0000</pubDate>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[gettext]]></category>
		<category><![CDATA[multilingue]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tradution]]></category>
		<guid isPermaLink="false">https://programmation.surleweb-france.fr/?p=952</guid>

					<description><![CDATA[<p>Pour internationaliser son code python, la mise en place d'un appli Python multilingue facilement grâce à la librairie gettext</p>
<p class="continue-reading-button"> <a class="continue-reading-link" href="https://programmation.surleweb-france.fr/python-creer-des-traductions-pour-son-application/">Continuer la lecture<i class="crycon-right-dir"></i></a></p>
<p>L’article <a href="https://programmation.surleweb-france.fr/python-creer-des-traductions-pour-son-application/">Python, créer des traductions pour son application</a> est apparu en premier sur <a href="https://programmation.surleweb-france.fr">La programmation sur le web</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Afin de toucher un publique plus large, il est parfois utile d&rsquo;avoir une application traduite dans plusieurs langues. Le module <strong><em><a href="https://docs.python.org/fr/3/library/gettext.html" target="_blank" rel="noreferrer noopener">gettext </a></em></strong>de Python permet la mise en place de traduction facilement, le tout dans un environnement Linux.</p>



<h2 class="wp-block-heading">Mise en place d&rsquo;une traduction</h2>



<p>Pour montrer son fonctionnement, on va utiliser un exemple simple mais qui sera efficace, tout d&rsquo;abord, on s&rsquo;occupe de notre dossier de travail :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">mkdir -p traduction/src
nano traduction/src/main.py</pre>



<p>Et on copie le code suivant dans le fichier <strong><em>main.py</em></strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def print_some_strings():
        print("Bonjour le monde")
        print("C'est une phrase traduite")

if __name__ == '__main__':
        print_some_strings()</pre>



<p>Les différentes traductions seront placées dans des dossiers, une branche pour une langue, dans notre cas, en français et en anglais :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">mkdir -p locales/fr/LC_MESSAGES
mkdir -p locales/en/LC_MESSAGES</pre>



<p>L&rsquo;arborescence devrait ressembler à cela :</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img decoding="async" width="193" height="125" src="//i1.wp.com/programmation.surleweb-france.fr/wp-content/uploads/2021/05/image-4.png" alt="" class="wp-image-953" srcset="https://i0.wp.com/programmation.surleweb-france.fr/wp-content/uploads/2021/05/image-4.png?w=193&amp;ssl=1 193w, https://i0.wp.com/programmation.surleweb-france.fr/wp-content/uploads/2021/05/image-4.png?resize=150%2C97&amp;ssl=1 150w" sizes="(max-width: 193px) 100vw, 193px" /></figure></div>



<p>Une fois cela fait, nous allons nous concentrer sur notre script main.py, il va falloir :</p>



<ul class="wp-block-list"><li>importer le module</li><li>identifier les parties à traduire</li></ul>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import gettext

_ = gettext.gettext

def print_some_strings():
        print(_("Bonjour le monde"))
        print(_("C'est une phrase traduite"))

if __name__ == '__main__':
        print_some_strings()</pre>



<p>Sur la première ligne, nous reconnaissons l&rsquo;import du module, rien de compliqué, nous venons marquer le texte avec le « <strong>_</strong>« .</p>



<p>Maintenant, passons à l&rsquo;édition de nos différents fichiers, nous allons éditer plusieurs fichiers :</p>



<ul class="wp-block-list"><li>« <strong><em>.pot</em></strong> » est le patron de la traduction, c&rsquo;est un fichier sans traduction dans lequel sont listés les éléments à traduire</li><li>« <strong><em>.po</em></strong> » est le fichier de traduction dans lequel nous mettrons les traductions</li><li>« <strong><em>.mo</em></strong> » est la transcription du fichier précédent mais compréhensible par l&rsquo;application python</li></ul>



<p>Commençons par générer le fichier « <strong><em>.pot</em></strong> » :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pygettext -d main -o locales/main.pot src/main.py</pre>



<p>Cela va générer notre fichier brut :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR ORGANIZATION
# FIRST AUTHOR &lt;EMAIL@ADDRESS>, YEAR.
#
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"POT-Creation-Date: 2021-05-05 20:33+CEST\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME &lt;EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE &lt;LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: ENCODING\n"
"Generated-By: pygettext.py 1.5\n"


#: src/main.py:13
msgid "Bonjour le monde"
msgstr ""

#: src/main.py:14
msgid "C'est une phrase traduite"
msgstr ""</pre>



<p>Tu peux déjà y mettre les adresses mail, il faut surtout remplacer <strong>CHARSET </strong>et <strong>ENCODING </strong>respectivement par <strong>UTF-8</strong> et <strong>8-bit</strong>.</p>



<p>On va générer le fichier pour chaque langue avec la commande suivante (à faire pour chaque langue, ici le français):</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">msginit -l fr -i locales/main.pot -o locales/fr/LC_MESSAGES/main.po</pre>



<p>Il faut mettre en place dans chacun de ces nouveaux fichiers les traductions, une fois cela fait, il nous reste à créer le <strong><em>.mo</em></strong> qui sera utilisé par l&rsquo;application :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cd locales/fr/LC_MESSAGES # ou fr est à remplacer en fonction des langues
msgfmt main.po -o main.mo</pre>



<p>Maintenant, retournons au code Python, pour utiliser l&rsquo;une ou l&rsquo;autre traduction :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import gettext

en = gettext.translation('main', localedir='locales', languages=['en'])
en.install()
_ = en.gettext # en anglais
ngettext = en.ngettext

def print_some_strings():
        print(_("Bonjour le monde"))
        print(_("C'est une phrase traduite"))

if __name__ == '__main__':
        print_some_strings()</pre>



<p>Une fois exécuté, le résultat sera les phrases traduites.</p>



<h2 class="wp-block-heading">Mise à jour de la traduction</h2>



<p>Pour mettre à jour la traduction, bien entendu sans perdre celles déjà faite, après avoir modifié le fichier <strong><em>main.py</em></strong>, Lance la commande :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pygettext -p locales -d main src/main.py
cd locales
msgmerge --update en/LC_MESSAGES/main.po main.pot</pre>



<p>Mettre en place la traduction, puis regénérer le fichier <strong><em>.mo </em></strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cd fr/LC_MESSAGES/ # à faire pour chaque langue
msgfmt main.po -o main.mo</pre>



<h2 class="wp-block-heading">Cas de la pluralisation</h2>



<p>Nous pouvons prendre en compte la pluralisation dans la langue à traduire.</p>



<p>Nous allons continuer de prendre notre exemple, en y ajoutant une fonction pour illustrer ce cas :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import gettext

en = gettext.translation('main', localedir='locales', languages=['en'])
en.install()
_ = en.gettext # en anglais

def print_some_strings():
        print(_("Bonjour le monde"))
        print(_("C'est une phrase traduite"))
def print_some_plural_strings(num):
    message1 = ngettext('{0} homme', '{0} hommes', num)
    message2 = ngettext('Je possede {0} portable', 'Je possede {0} portables', num)

if __name__ == '__main__':
        print_some_plural_strings(1)
        print_some_plural_strings(5)</pre>



<p>La commande <strong>pygettext </strong>ne fonctionne pas dans mon cas pour générer le template (<strong><em>.pot</em></strong>), utilise la commande suivante :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">xgettext -L Python -o locales/main.pot src/main.py</pre>



<p>Cela va générer le nouveau template :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR &lt;EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2021-05-08 10:26+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME &lt;EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE &lt;LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"

#: src/main.py:9
msgid "Bonjour le monde"
msgstr ""

#: src/main.py:10
msgid "C'est une phrase traduite"
msgstr ""

#: src/main.py:12
#, python-brace-format
msgid "{0} homme"
msgid_plural "{0} hommes"
msgstr[0] ""
msgstr[1] ""

#: src/main.py:13
#, python-brace-format
msgid "Je possede {0} portable"
msgid_plural "Je possede {0} portables"
msgstr[0] ""
msgstr[1] ""</pre>



<p>Nous allons fusionner ce nouveau template pour obtenir notre nouveau fichier .po pour chaque langue :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Si besoin se mettre dans locales avec cd locales
msgmerge --update fr/LC_MESSAGES/main.po main.pot # remplacer fr par sa langue</pre>



<p>Une fois cela fait, tu peux traduire les fichiers pour chaque langue.</p>



<p>Pour finir, nous mettrons à jour les fichiers <strong><em>.mo</em></strong> :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="shell" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># faire en fonction de la langue
cd locales/fr/LC_MESSAGES
msgfmt main.po -o main.mo</pre>



<p>Une fois cela fait, en lançant le script, tu devrais obtenir :</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img fetchpriority="high" decoding="async" width="657" height="109" src="//i0.wp.com/programmation.surleweb-france.fr/wp-content/uploads/2021/05/image-5.png" alt="" class="wp-image-957" srcset="https://i0.wp.com/programmation.surleweb-france.fr/wp-content/uploads/2021/05/image-5.png?w=657&amp;ssl=1 657w, https://i0.wp.com/programmation.surleweb-france.fr/wp-content/uploads/2021/05/image-5.png?resize=300%2C50&amp;ssl=1 300w, https://i0.wp.com/programmation.surleweb-france.fr/wp-content/uploads/2021/05/image-5.png?resize=150%2C25&amp;ssl=1 150w" sizes="(max-width: 657px) 100vw, 657px" /></figure></div>



<p>Si il y a une erreur dans le fichier .po de langue qui s&rsquo;affiche, le terminal indiquera une erreur dans le script main.py sans préciser que l&rsquo;erreur vient de l&rsquo;autre fichier.</p>



<h2 class="wp-block-heading">Conclusion</h2>



<p>Bien que cela peut paraître fastidieux, il est simple de mettre en place une appli multilingue en python grâce à la librairie <strong><em>gettext</em></strong>. Celle-ci est également disponible dans d&rsquo;autres langage.</p>
<p>L’article <a href="https://programmation.surleweb-france.fr/python-creer-des-traductions-pour-son-application/">Python, créer des traductions pour son application</a> est apparu en premier sur <a href="https://programmation.surleweb-france.fr">La programmation sur le web</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programmation.surleweb-france.fr/python-creer-des-traductions-pour-son-application/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">952</post-id>	</item>
	</channel>
</rss>
