Python changing keywords name

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Jun 23 22:14:42 EDT 2007


vedrandeko... at v-programs.com wrote:

> I  on working on windows and Python 2.4. Where can I find and CHANGE
> python
> grammar.  ( I just want to change the keywords )

Instead of changing Python grammar, you could convert your
"translated" source into "original" Python using the code below, and
compile and run as usual; you can also reverse the process. Also, this
lets you use the standard Python library and all other Python code
around the world.
Unlike a simple "search and replace", it understands the lexical
structure of a Python program, and won't replace a keyword inside a
quoted string, by example.
The core function is simple:

def translate_tokens(sourcefile, tdict):
    for tok_num, tok_val, _, _, _ in
tokenize.generate_tokens(sourcefile.readline):
        if tok_num==token.NAME: tok_val = tdict.get(tok_val, tok_val)
        yield tok_num, tok_val

translated_code = tokenize.untokenize(
  translate_tokens(StringIO(original_code), translation_dictionary))

Note that you may encounter problems if the original code uses some
names matching the translated keywords.

(I hope nobody will abuse this technique... Y perdón a los
hispanoparlantes por lo horrible de la traducción).

--- begin code ---
from cStringIO import StringIO
import token
import tokenize

# "spanished" Python source from the SimplePrograms wiki page
code_es = r"""
BOARD_SIZE = 8

clase BailOut(Exception):
    pasar

def validate(queens):
    left = right = col = queens[-1]
    para r en reversed(queens[:-1]):
        left, right = left-1, right+1
        si r en (left, col, right):
            lanzar BailOut

def add_queen(queens):
    para i en range(BOARD_SIZE):
        test_queens = queens + [i]
        intentar:
            validate(test_queens)
            si len(test_queens) == BOARD_SIZE:
                retornar test_queens
            else:
                retornar add_queen(test_queens)
        excepto BailOut:
            pasar
    lanzar BailOut

queens = add_queen([])
imprimir queens
imprimir "\n".join(". "*q + "Q " + ". "*(BOARD_SIZE-q-1) para q en
queens)
"""

# english keyword -> spanish
trans_en2es = {
    'and': 'y',
    'as': 'como',
    'assert': 'afirmar',
    'break': 'afuera',
    'class': 'clase',
    'continue': 'siguiente',
    'def': 'def',
    'del': 'elim',
    'elif': 'sinosi',
    'else': 'sino',
    'except': 'excepto',
    'exec': 'ejecutar',
    'finally': 'finalmente',
    'for': 'para',
    'from': 'desde',
    'global': 'global',
    'if': 'si',
    'import': 'importar',
    'in': 'en',
    'is': 'es',
    'lambda': 'lambda',
    'not': 'no',
    'or': 'o',
    'pass': 'pasar',
    'print': 'imprimir',
    'raise': 'lanzar',
    'return': 'retornar',
    'try': 'intentar',
    'while': 'mientras',
    'with': 'con',
    'yield': 'producir',
}
# reverse dict
trans_es2en = dict((v,k) for (k,v) in trans_en2es.items())

def translate_tokens(source, tdict):
    for tok_num, tok_val, _, _, _ in
tokenize.generate_tokens(source.readline):
        if tok_num==token.NAME: tok_val = tdict.get(tok_val, tok_val)
        yield tok_num, tok_val

code_en = tokenize.untokenize(translate_tokens(StringIO(code_es),
trans_es2en))
print code_en
code_es2= tokenize.untokenize(translate_tokens(StringIO(code_en),
trans_en2es))
print code_es2
--- end code ---

--
Gabriel Genellina

PS: Asking just once is enough.




More information about the Python-list mailing list