Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Script rst2po.py to migrate tutorial.python.org.ar to this new version #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 30 commits into from
May 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
3be6970
Tutorial PyAr submodule
humitos May 2, 2020
f71c1fd
rst2po.py
humitos May 2, 2020
3951c61
Skel for the rst2po.py script
humitos May 2, 2020
3cea73b
Merge branch '3.7' into rst2po
humitos May 2, 2020
8cbe9ed
About to start the (english, spanish) mapping list
humitos May 2, 2020
a274828
Merge branch '3.7' of github.com:raulcd/python-docs-es into rst2po
humitos May 2, 2020
5e07374
Merge branch 'rst2po' of github.com:raulcd/python-docs-es into rst2po
humitos May 2, 2020
25b5aa7
Initial working version of rst2po.py
humitos May 2, 2020
9ff4f8c
Only save translated files
humitos May 2, 2020
cfb3344
Use tutorialpyar with fixes
humitos May 2, 2020
4a30a79
First pass reviewed
humitos May 2, 2020
7f679cf
ignore ! when comparing
gilgamezh May 2, 2020
5144e29
update translation
gilgamezh May 2, 2020
d7569d2
More translations
humitos May 2, 2020
ae92662
Merge branch 'rst2po' of github.com:raulcd/python-docs-es into rst2po
humitos May 2, 2020
72b4d3d
More inputoutput
humitos May 2, 2020
cf3a545
update datastructures.po translation (migration)
gilgamezh May 2, 2020
08e56cc
Update tutorialpyar submodule
humitos May 2, 2020
2b39104
update datastructures.po translation (migration)
gilgamezh May 2, 2020
7e9682c
update datastructures.po translation (migration)
gilgamezh May 2, 2020
5ba9b04
Merge branch 'rst2po' of github.com:raulcd/python-docs-es into rst2po
gilgamezh May 2, 2020
bfc7aec
Classes
humitos May 2, 2020
2a7a07f
Update tutorialpyar with fixes
humitos May 2, 2020
81a7350
Merge branch 'rst2po' of github.com:raulcd/python-docs-es into rst2po
humitos May 2, 2020
76368ac
Translate errors.po
humitos May 2, 2020
0dc54d5
modules.po
humitos May 2, 2020
a4d592e
stdlib.po translated from pyar tutorial
humitos May 2, 2020
3b5c9d0
update stdlib2 translation (migration)
gilgamezh May 2, 2020
edd1505
update stdlib2 translation (migration)
gilgamezh May 2, 2020
322f1a7
update submodule
gilgamezh May 2, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@
url = https://github.com/python/cpython.git
branch = 3.7
shallow = true
[submodule "tutorialpyar"]
path = .migration/tutorialpyar
url = https://github.com/pyar/tutorial.git
134 changes: 134 additions & 0 deletions .migration/rst2po.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
# rst2po.py
# Script to migrate the Python official tutorial that we have already translated in PyAr
# (https://github.com/PyAr/tutorial) from reStructuredText to the new official translation format (.po)
#
# It parses the .rst and compare sentence/paragraph by sentence/paragraph and if the match is exact,
# and there is no translation for that sentence/paragraph it updates the .po file with the translated text
# from the .rst file.

import re
import glob
import os
import polib # fades


PO_DIR = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'..',
))

RST_TRADUCIDOS_DIR = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'tutorialpyar',
'traducidos',
))

RST_ORIGINAL_DIR = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
'tutorialpyar',
'original',
))



def get_rst_file(pofilename):
"""Given a .po filename returns the corresponding .rst filename"""
basename = os.path.basename(pofilename)
basename, ext = basename.rsplit('.', 1)
rstfilename = os.path.join(RST_TRADUCIDOS_DIR, f'{basename}.rst')
if os.path.exists(rstfilename):
return rstfilename


def get_rst_original_filename(rstfilename):
rst_original_filename = ''
if rstfilename.endswith('real-index.rst'):
rst_original_filename = 'index.rst'

basename = os.path.basename(rst_original_filename or rstfilename)
rst_original_filename = os.path.join(RST_ORIGINAL_DIR, basename)
if os.path.exists(rst_original_filename):
return rst_original_filename


def create_english_spanish_sentences(rstfilename):
"""Create a tuple of (english, spanish) sentences for rstfilename"""

def get_paragraph(fd):
lines = []
paragraph = []
for line in fd.read().splitlines():
# import pdb; pdb.set_trace()
if any([
line.startswith('.. '),
line.startswith('==='),
line.startswith('---'),
line.startswith('***'),
]):
continue

if line == '' and not paragraph:
continue

if line == '':
lines.append(' '.join(paragraph))
paragraph = []
continue
paragraph.append(line)

return lines

# NOTE: we could use docutils and parse the rst in the correct way, but
# that will probably take more time
with open(get_rst_original_filename(rstfilename)) as fd:
english = get_paragraph(fd)

with open(rstfilename) as fd:
spanish = get_paragraph(fd)

result = list(zip(english, spanish))
return result


def get_rst_translation_text(rstfilename, english_spanish, text):
"""Given an rstfilename an a text returns the corresponding translated text if exists"""
for en, es in english_spanish:
if en.replace("!", "") == text.replace("!", ""):
return es


def update_po_translation(pofilename, english, spanish):
"""Update the pofilename with the translated spanish text"""
pass


for pofilename in glob.glob(PO_DIR + '**/*/*.po'):
translated = False
rstfilename = get_rst_file(pofilename)
if rstfilename is None:
continue

english_spanish = create_english_spanish_sentences(rstfilename)

po = polib.pofile(pofilename)
for entry in po:
english_text = entry.msgid
spanish_text = entry.msgstr
if spanish_text:
# Do not override already translated text
continue

translated_text = get_rst_translation_text(rstfilename, english_spanish, english_text)
if translated_text is None:
continue

translated = True

entry.msgstr = translated_text
# update_po_translation(po, english_text, translated_text)

if translated:
po.save(pofilename)
1 change: 1 addition & 0 deletions .migration/tutorialpyar
Submodule tutorialpyar added at 0349d8
121 changes: 91 additions & 30 deletions tutorial/appendix.po
Original file line number Diff line number Diff line change
Expand Up @@ -18,63 +18,90 @@ msgstr ""

#: ../Doc/tutorial/appendix.rst:5
msgid "Appendix"
msgstr ""
msgstr "Apéndice"

#: ../Doc/tutorial/appendix.rst:11
msgid "Interactive Mode"
msgstr ""
msgstr "Modo interactivo"

#: ../Doc/tutorial/appendix.rst:16
msgid "Error Handling"
msgstr ""
msgstr "Manejo de errores"

#: ../Doc/tutorial/appendix.rst:18
msgid ""
"When an error occurs, the interpreter prints an error message and a stack "
"trace. In interactive mode, it then returns to the primary prompt; when "
"input came from a file, it exits with a nonzero exit status after printing "
"the stack trace. (Exceptions handled by an :keyword:`except` clause in a :"
"keyword:`try` statement are not errors in this context.) Some errors are "
"unconditionally fatal and cause an exit with a nonzero exit; this applies to "
"internal inconsistencies and some cases of running out of memory. All error "
"messages are written to the standard error stream; normal output from "
"the stack trace. (Exceptions handled by an :keyword:`except` clause in a "
":keyword:`try` statement are not errors in this context.) Some errors are "
"unconditionally fatal and cause an exit with a nonzero exit; this applies to"
" internal inconsistencies and some cases of running out of memory. All "
"error messages are written to the standard error stream; normal output from "
"executed commands is written to standard output."
msgstr ""
"Cuando ocurre un error, el intérprete imprime un mensaje de error y la traza"
" del error. En el modo interactivo, luego retorna al prompt primario; "
"cuando la entrada viene de un archivo, el programa termina con código de "
"salida distinto a cero luego de imprimir la traza del error. (Las "
"excepciones manejadas por una clausula :keyword:`except` en una sentencia "
":keyword:`try` no son errores en este contexto). Algunos errores son "
"incondicionalmente fatales y causan una terminación con código de salida "
"distinto de cero; esto se debe a inconsistencias internas o a que el "
"intérprete se queda sin memoria. Todos los mensajes de error se escriben en "
"el flujo de errores estándar; las salidas normales de comandos ejecutados se"
" escriben en la salida estándar."

#: ../Doc/tutorial/appendix.rst:28
msgid ""
"Typing the interrupt character (usually :kbd:`Control-C` or :kbd:`Delete`) "
"to the primary or secondary prompt cancels the input and returns to the "
"primary prompt. [#]_ Typing an interrupt while a command is executing raises "
"the :exc:`KeyboardInterrupt` exception, which may be handled by a :keyword:"
"`try` statement."
"primary prompt. [#]_ Typing an interrupt while a command is executing raises"
" the :exc:`KeyboardInterrupt` exception, which may be handled by a "
":keyword:`try` statement."
msgstr ""
"Al ingresar el caracter de interrupción (por lo general :kbd:`Control-C` o "
":kbd:`Supr`) en el prompt primario o secundario, se cancela la entrada y "
"retorna al prompt primario. [#]_ Tipear una interrupción mientras un "
"comando se están ejecutando lanza la excepción :exc:`KeyboardInterrupt`, que"
" puede ser manejada con una sentencia :keyword:`try`."

#: ../Doc/tutorial/appendix.rst:38
msgid "Executable Python Scripts"
msgstr ""
msgstr "Programas ejecutables de Python"

#: ../Doc/tutorial/appendix.rst:40
msgid ""
"On BSD'ish Unix systems, Python scripts can be made directly executable, "
"like shell scripts, by putting the line ::"
msgstr ""
"En los sistemas Unix y tipo BSD, los programas Python pueden convertirse "
"directamente en ejecutables, como programas del intérprete de comandos, "
"poniendo la linea::"

#: ../Doc/tutorial/appendix.rst:45
msgid ""
"(assuming that the interpreter is on the user's :envvar:`PATH`) at the "
"beginning of the script and giving the file an executable mode. The ``#!`` "
"must be the first two characters of the file. On some platforms, this first "
"line must end with a Unix-style line ending (``'\\n'``), not a Windows "
"must be the first two characters of the file. On some platforms, this first"
" line must end with a Unix-style line ending (``'\\n'``), not a Windows "
"(``'\\r\\n'``) line ending. Note that the hash, or pound, character, "
"``'#'``, is used to start a comment in Python."
msgstr ""
"...al principio del script y dándole al archivo permisos de ejecución "
"(asumiendo que el intérprete están en la variable de entorno :envvar:`PATH` "
"del usuario). ``#!`` deben ser los primeros dos caracteres del archivo. En"
" algunas plataformas, la primera línea debe terminar al estilo Unix "
"(``'\\n'``), no como en Windows (``'\\r\\n'``). Notá que el caracter "
"numeral ``'#'`` se usa en Python para comenzar un comentario."

#: ../Doc/tutorial/appendix.rst:52
msgid ""
"The script can be given an executable mode, or permission, using the :"
"program:`chmod` command."
"The script can be given an executable mode, or permission, using the "
":program:`chmod` command."
msgstr ""
"Se le puede dar permisos de ejecución al script usando el comando "
":program:`chmod`::"

#: ../Doc/tutorial/appendix.rst:59
msgid ""
Expand All @@ -84,10 +111,15 @@ msgid ""
"extension can also be ``.pyw``, in that case, the console window that "
"normally appears is suppressed."
msgstr ""
"En sistemas Windows, no existe la noción de \"modo ejecutable\". El "
"instalador de Python asocia automáticamente la extensión ``.py`` con "
"``python.exe`` para que al hacerle doble click a un archivo Python se corra "
"el script. La extensión también puede ser ``.pyw``, en este caso se omite "
"la ventana con la consola que normalmente aparece."

#: ../Doc/tutorial/appendix.rst:69
msgid "The Interactive Startup File"
msgstr ""
msgstr "El archivo de inicio interactivo"

#: ../Doc/tutorial/appendix.rst:71
msgid ""
Expand All @@ -97,54 +129,83 @@ msgid ""
"the name of a file containing your start-up commands. This is similar to "
"the :file:`.profile` feature of the Unix shells."
msgstr ""
"Cuando usás Python en forma interactiva, suele ser útil que algunos comandos"
" estándar se ejecuten cada vez que el intérprete se inicia. Podés hacer "
"esto configurando la variable de entorno :envvar:`PYTHONSTARTUP` con el "
"nombre de un archivo que contenga tus comandos de inicio. Esto es similar "
"al archivo :file:`.profile` en los intérpretes de comandos de Unix."

#: ../Doc/tutorial/appendix.rst:77
msgid ""
"This file is only read in interactive sessions, not when Python reads "
"commands from a script, and not when :file:`/dev/tty` is given as the "
"explicit source of commands (which otherwise behaves like an interactive "
"session). It is executed in the same namespace where interactive commands "
"are executed, so that objects that it defines or imports can be used without "
"qualification in the interactive session. You can also change the prompts "
"are executed, so that objects that it defines or imports can be used without"
" qualification in the interactive session. You can also change the prompts "
"``sys.ps1`` and ``sys.ps2`` in this file."
msgstr ""
"Este archivo es solo leído en las sesiones interactivas del intérprete, no "
"cuando Python lee comandos de un script ni cuando :file:`/dev/tty` se "
"explicita como una fuente de comandos (que de otro modo se comporta como una"
" sesión interactiva). Se ejecuta en el mismo espacio de nombres en el que "
"los comandos interactivos se ejecutan, entonces los objetos que define o "
"importa pueden ser usados sin cualificaciones en la sesión interactiva. En "
"este archivo también podés cambiar los prompts ``sys.ps1`` y ``sys.ps2``."

#: ../Doc/tutorial/appendix.rst:85
msgid ""
"If you want to read an additional start-up file from the current directory, "
"you can program this in the global start-up file using code like ``if os."
"path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())``. If you "
"want to use the startup file in a script, you must do this explicitly in the "
"script::"
"you can program this in the global start-up file using code like ``if "
"os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())``. If you "
"want to use the startup file in a script, you must do this explicitly in the"
" script::"
msgstr ""
"Si querés leer un archivo de inicio adicional desde el directorio actual, "
"podés programarlo en el archivo de inicio global usando algo como ``if "
"os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())``. Si "
"querés usar el archivo de inicio en un script, tenés que hacer lo siguiente "
"de forma explícita en el script::"

#: ../Doc/tutorial/appendix.rst:102
msgid "The Customization Modules"
msgstr ""
msgstr "Los módulos de customización"

#: ../Doc/tutorial/appendix.rst:104
msgid ""
"Python provides two hooks to let you customize it: :mod:`sitecustomize` and :"
"mod:`usercustomize`. To see how it works, you need first to find the "
"Python provides two hooks to let you customize it: :mod:`sitecustomize` and "
":mod:`usercustomize`. To see how it works, you need first to find the "
"location of your user site-packages directory. Start Python and run this "
"code::"
msgstr ""
"Python provee dos formas para customizarlo: :mod:`sitecustomize` y "
":mod:`usercustomize`. Para ver como funciona, necesitás primero encontrar "
"dónde está tu directorio para tu usuario de paquetes del sistema. Arrancá "
"Python y ejecutá el siguiente código::"

#: ../Doc/tutorial/appendix.rst:112
msgid ""
"Now you can create a file named :file:`usercustomize.py` in that directory "
"and put anything you want in it. It will affect every invocation of Python, "
"unless it is started with the :option:`-s` option to disable the automatic "
"and put anything you want in it. It will affect every invocation of Python,"
" unless it is started with the :option:`-s` option to disable the automatic "
"import."
msgstr ""
"Ahora podés crear un archivo llamado :file:`usercustomize.py` en ese "
"directorio y poner lo que quieras en él. Eso afectará cada ejecución de "
"Python, a menos que se arranque con la opción :option:`-s` para deshabilitar"
" esta importación automática."

#: ../Doc/tutorial/appendix.rst:116
msgid ""
":mod:`sitecustomize` works in the same way, but is typically created by an "
"administrator of the computer in the global site-packages directory, and is "
"imported before :mod:`usercustomize`. See the documentation of the :mod:"
"`site` module for more details."
"imported before :mod:`usercustomize`. See the documentation of the "
":mod:`site` module for more details."
msgstr ""
":mod:`sitecustomize` funciona de la misma manera, pero normalmente lo crea "
"el administrador de la computadora en el directorio global de paquetes para "
"el sistema, y se importa antes que :mod:`usercustomize`. Para más detalles, "
"mirá la documentación del módulo :mod:`site`."

#: ../Doc/tutorial/appendix.rst:123
msgid "Footnotes"
Expand Down
Loading