웹사이트 검색

PyGObject 응용 프로그램을 다른 언어로 번역하기 – 5부


우리는 여러분과 함께 PyGObject 프로그래밍 시리즈를 계속하고 있으며 이번 다섯 번째 부분에서는 PyGObject 애플리케이션을 다른 언어로 번역하는 방법을 배우겠습니다. 전 세계에 애플리케이션을 게시하려면 애플리케이션을 번역하는 것이 중요합니다. 모든 사람이 영어를 이해하는 것은 아니기 때문에 최종 사용자에게 더 사용자 친화적일 것입니다.

번역 프로세스의 작동 방식

다음 단계를 사용하여 Linux 데스크탑에서 프로그램을 번역하는 단계를 요약할 수 있습니다.

  1. Python 파일에서 번역 가능한 문자열을 추출합니다.
  2. 나중에 다른 언어로 번역할 수 있는 형식인 .pot 파일에 문자열을 저장합니다.
  3. 문자열 번역을 시작합니다.
  4. 새로 번역된 문자열을 시스템 언어가 변경될 때 자동으로 사용되는 .po 파일로 내보냅니다.
  5. 기본 Python 파일과 .desktop 파일에 몇 가지 작은 프로그래밍 변경 사항을 추가합니다.

그리고 그게 다야! 이 단계를 수행하면 전 세계의 최종 사용자가 애플리케이션을 사용할 수 있게 됩니다. (그렇지만 프로그램을 전 세계 모든 언어로 번역해야 합니다!), 참 쉽지 않나요? :-)

먼저 시간을 절약하려면 아래 링크에서 프로젝트 파일을 다운로드하고 홈 디렉터리에 파일을 추출하세요.

  1. https://copy.com/TjyZAaNgeQ6BB7yn

"setup.py" 파일을 열고 변경 사항을 확인하세요.

Here we imported the 'setup' module which allows us to install Python scripts to the local system beside performing some other tasks, you can find the documentation here: https://docs.python.org/2/distutils/apiref.html
from distutils.core import setup

Those modules will help us in creating the translation files for the program automatically.
from subprocess import call
from glob import glob
from os.path import splitext, split

DON'T FOTGET TO REPLACE 'myprogram' WITH THE NAME OF YOUR PROGRAM IN EVERY FILE IN THIS PROJECT.

data_files = [ ("lib/myprogram", ["ui.glade"]), # This is going to install the "ui.glade" file under the /usr/lib/myprogram path.
                     ("share/applications", ["myprogram.desktop"]) ] 

This code does everything needed for creating the translation files, first it will look for all the .po files inside the po folder, then it will define the default path for where to install the translation files (.mo) on the local system, then it's going to create the directory on the local system for the translation files of our program and finally it's going to convert all the .po files into .mo files using the "msgfmt" command.
po_files = glob("po/*.po")
for po_file in po_files:
  lang = splitext(split(po_file)[1])[0]
  mo_path = "locale/{}/LC_MESSAGES/myprogram.mo".format(lang)
Make locale directories
  call("mkdir -p locale/{}/LC_MESSAGES/".format(lang), shell=True)
Generate mo files
  call("msgfmt {} -o {}".format(po_file, mo_path), shell=True)
  locales = map(lambda i: ('share/'+i, [i+'/myprogram.mo', ]), glob('locale/*/LC_MESSAGES'))

Here, the installer will automatically add the .mo files to the data files to install them later.
  data_files.extend(locales)

setup(name = "myprogram", # Name of the program.
      version = "1.0", # Version of the program.
      description = "An easy-to-use web interface to create & share pastes easily", # You don't need any help here.
      author = "TecMint", # Nor here.
      author_email = "[email ",# Nor here :D
      url = "http://example.com", # If you have a website for you program.. put it here.
      license='GPLv3', # The license of the program.
      scripts=['myprogram'], # This is the name of the main Python script file, in our case it's "myprogram", it's the file that we added under the "myprogram" folder.

Here you can choose where do you want to install your files on the local system, the "myprogram" file will be automatically installed in its correct place later, so you have only to choose where do you want to install the optional files that you shape with the Python script
      data_files=data_files) # And this is going to install the .desktop file under the /usr/share/applications folder, all the folder are automatically installed under the /usr folder in your root partition, you don't need to add "/usr/ to the path.

또한 “myprogram” 파일을 열고 우리가 수행한 프로그래밍 방식 변경 사항을 확인하세요. 모든 변경 사항은 주석에 설명되어 있습니다.

#!/usr/bin/python 
-*- coding: utf-8 -*- 

## Replace your name and email.
My Name <[email >

## Here you must add the license of the file, replace "MyProgram" with your program name.
License:
   MyProgram is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.
#
   MyProgram is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
#
   You should have received a copy of the GNU General Public License
   along with MyProgram.  If not, see <http://www.gnu.org/licenses/>.

from gi.repository import Gtk 
import os, gettext, locale

## This is the programmatic change that you need to add to the Python file, just replace "myprogram" with the name of your program. The "locale" and "gettext" modules will take care about the rest of the operation.
locale.setlocale(locale.LC_ALL, '')
gettext.bindtextdomain('myprogram', '/usr/share/locale')
gettext.textdomain('myprogram')
_ = gettext.gettext
gettext.install("myprogram", "/usr/share/locale")

class Handler: 
  
  def openterminal(self, button): 
    ## When the user clicks on the first button, the terminal will be opened.
    os.system("x-terminal-emulator ")
  
  def closeprogram(self, button):
    Gtk.main_quit()
    
Nothing new here.. We just imported the 'ui.glade' file. 
builder = Gtk.Builder() 
builder.add_from_file("/usr/lib/myprogram/ui.glade") 
builder.connect_signals(Handler()) 

label = builder.get_object("label1")
Here's another small change, instead of setting the text to ("Welcome to my Test program!") we must add a "_" char before it in order to allow the responsible scripts about the translation process to recognize that it's a translatable string.
label.set_text(_("Welcome to my Test program !"))

button = builder.get_object("button2")
And here's the same thing.. You must do this for all the texts in your program, elsewhere, they won't be translated.
button.set_label(_("Click on me to open the Terminal"))


window = builder.get_object("window1") 
window.connect("delete-event", Gtk.main_quit)
window.show_all() 
Gtk.main()

이제.. 프로그램 번역을 시작하겠습니다. 먼저 .pot 파일(프로그램에서 번역 가능한 모든 문자열이 포함된 파일)을 생성하여
다음 명령을 사용하여 번역을 시작할 수 있습니다:

cd myprogram
xgettext --language=Python --keyword=_ -o po/myprogram.pot myprogram

그러면 다음 코드가 포함된 기본 프로젝트 폴더의 “po” 폴더 내에 “myprogram.pot” 파일이 생성됩니다.

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 <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2014-12-29 21:28+0200\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <[email >\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=CHARSET\n"
"Content-Transfer-Encoding: 8bit\n"

#: myprogram:48
msgid "Welcome to my Test program !"
msgstr ""

#: myprogram:52
msgid "Click on me to open the Terminal"
msgstr ""

이제 문자열 번역을 시작하려면.. "po" 안에 있는 "ISO-639-1 " 언어 코드를 사용하여 프로그램을 번역하려는 각 언어에 대해 별도의 파일을 만듭니다. ” 폴더, 예를 들어 프로그램을 아랍어로 번역하려면 “ar.po”라는 파일을 만들고 “ myprogram.pot ” 파일을 복사하세요.

프로그램을 독일어로 번역하려면 “de.po” 파일을 만들고 “myprogram.pot”의 내용을 복사하세요. 파일을 그것에.. 따라서 프로그램을 번역하려는 각 언어에 대한 파일을 만들어야 합니다.

이제 “ar.po” 파일 작업을 하고 “myprogram.pot” 파일의 내용을 복사하여 해당 파일에 넣고 다음을 편집합니다. :

  1. 설명 제목: 원하는 경우 여기에 프로젝트 제목을 입력할 수 있습니다.
  2. 패키지의 저작권 보유자 연도: 프로젝트를 만든 연도로 바꾸세요.
  3. PACKAGE: 패키지 이름으로 바꿉니다.
  4. 제1저자 , 연도: 이를 실제 이름, 이메일 및 파일을 번역한 연도로 바꾸세요.
  5. 패키지 버전: debian/control 파일의 패키지 버전으로 바꿉니다.
  6. YEAR-MO-DA HO:MI+ZONE: 설명이 필요 없으며 원하는 날짜로 변경할 수 있습니다.
  7. 전체 이름 : 이름과 이메일도 바꾸세요.
  8. Language-Team: 번역하려는 언어의 이름(예: "아랍어" 또는 "프랑스어")으로 바꿉니다.
  9. 언어: 여기에 번역하려는 언어에 대한 ISO-639-1 코드를 삽입해야 합니다(예: "ar ", "fr ", "de "..etc). 여기에서 전체 목록을 찾으세요.
  10. CHARSET: 이 단계는 중요합니다. 이 문자열을 대부분의 언어를 지원하는 "UTF-8 "(따옴표 제외)로 바꾸세요.

이제 번역을 시작해보세요! “msgstr”의 따옴표 뒤에 각 문자열에 대한 번역을 추가하세요. 파일을 저장하고 종료합니다.
에 대한 좋은 번역 파일 예를 들어 아랍어는 다음과 같습니다.

My Program
Copyright (C) 2014
This file is distributed under the same license as the myprogram package.
Hanny Helal <[email <, 2014.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: 1.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2014-12-29 21:28+0200\n"
"PO-Revision-Date: 2014-12-29 22:28+0200\n"
"Last-Translator: M.Hanny Sabbagh <hannysabbagh<@hotmail.com<\n"
"Language-Team: Arabic <[email <\n"
"Language: ar\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

#: myprogram:48
msgid "Welcome to my Test program !"
msgstr "أهلًا بك إلى برنامجي الاختباري!"

#: myprogram:52
msgid "Click on me to open the Terminal"
msgstr "اضغط عليّ لفتح الطرفية"

더 이상 할 일이 없습니다. 다음 명령을 사용하여 프로그램을 패키징하면 됩니다.

debuild -us -uc

이제 다음 명령을 사용하여 새로 생성된 패키지를 설치해 보십시오.

sudo dpkg -i myprogram_1.0_all.deb

그리고 "언어 지원" 프로그램을 사용하거나 다른 프로그램을 사용하여 시스템 언어를 아랍어(또는 파일을 번역한 언어)로 변경하세요.

선택하면 프로그램이 아랍어로 번역됩니다.

여기에서 Linux 데스크톱용 PyGObject 프로그래밍에 대한 시리즈가 끝납니다. 물론 공식 문서와 Python GI API 참조에서 배울 수 있는 다른 내용도 많이 있습니다.

시리즈에 대해 어떻게 생각하시나요? 유용하다고 생각하시나요? 이 시리즈를 따라가며 첫 번째 애플리케이션을 만들 수 있었나요? 당신의 생각을 공유해주세요!