portugython 0.3.0__tar.gz → 0.4.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. portugython-0.4.1/CHANGELOG.md +151 -0
  2. {portugython-0.3.0 → portugython-0.4.1}/PKG-INFO +135 -32
  3. {portugython-0.3.0 → portugython-0.4.1}/README.md +133 -30
  4. {portugython-0.3.0 → portugython-0.4.1}/portugython/__init__.py +21 -4
  5. {portugython-0.3.0 → portugython-0.4.1}/portugython/_importador.py +85 -21
  6. portugython-0.4.1/portugython/transpilador.py +254 -0
  7. {portugython-0.3.0 → portugython-0.4.1}/pyproject.toml +5 -2
  8. portugython-0.4.1/tests/ola_mundo.ptpy +38 -0
  9. {portugython-0.3.0 → portugython-0.4.1}/tests/test_portugython.py +1 -1
  10. portugython-0.4.1/tests/test_transpilador.py +310 -0
  11. portugython-0.3.0/CHANGELOG.md +0 -91
  12. {portugython-0.3.0 → portugython-0.4.1}/.gitignore +0 -0
  13. {portugython-0.3.0 → portugython-0.4.1}/LICENSE +0 -0
  14. {portugython-0.3.0 → portugython-0.4.1}/portugython/abstrato.py +0 -0
  15. {portugython-0.3.0 → portugython-0.4.1}/portugython/aleatorio.py +0 -0
  16. {portugython-0.3.0 → portugython-0.4.1}/portugython/argumentos.py +0 -0
  17. {portugython-0.3.0 → portugython-0.4.1}/portugython/assincronico.py +0 -0
  18. {portugython-0.3.0 → portugython-0.4.1}/portugython/bisecao.py +0 -0
  19. {portugython-0.3.0 → portugython-0.4.1}/portugython/calendario.py +0 -0
  20. {portugython-0.3.0 → portugython-0.4.1}/portugython/caminho.py +0 -0
  21. {portugython-0.3.0 → portugython-0.4.1}/portugython/classe_dados.py +0 -0
  22. {portugython-0.3.0 → portugython-0.4.1}/portugython/codificacao.py +0 -0
  23. {portugython-0.3.0 → portugython-0.4.1}/portugython/colecoes.py +0 -0
  24. {portugython-0.3.0 → portugython-0.4.1}/portugython/compressao.py +0 -0
  25. {portugython-0.3.0 → portugython-0.4.1}/portugython/configuracao.py +0 -0
  26. {portugython-0.3.0 → portugython-0.4.1}/portugython/contexto.py +0 -0
  27. {portugython-0.3.0 → portugython-0.4.1}/portugython/copia.py +0 -0
  28. {portugython-0.3.0 → portugython-0.4.1}/portugython/csv_pt.py +0 -0
  29. {portugython-0.3.0 → portugython-0.4.1}/portugython/depuracao.py +0 -0
  30. {portugython-0.3.0 → portugython-0.4.1}/portugython/enumeracao.py +0 -0
  31. {portugython-0.3.0 → portugython-0.4.1}/portugython/estatistica.py +0 -0
  32. {portugython-0.3.0 → portugython-0.4.1}/portugython/estrutura.py +0 -0
  33. {portugython-0.3.0 → portugython-0.4.1}/portugython/expressao.py +0 -0
  34. {portugython-0.3.0 → portugython-0.4.1}/portugython/formatacao.py +0 -0
  35. {portugython-0.3.0 → portugython-0.4.1}/portugython/funcional.py +0 -0
  36. {portugython-0.3.0 → portugython-0.4.1}/portugython/hash_pt.py +0 -0
  37. {portugython-0.3.0 → portugython-0.4.1}/portugython/identificador.py +0 -0
  38. {portugython-0.3.0 → portugython-0.4.1}/portugython/iteradores.py +0 -0
  39. {portugython-0.3.0 → portugython-0.4.1}/portugython/json.py +0 -0
  40. {portugython-0.3.0 → portugython-0.4.1}/portugython/matematica.py +0 -0
  41. {portugython-0.3.0 → portugython-0.4.1}/portugython/py.typed +0 -0
  42. {portugython-0.3.0 → portugython-0.4.1}/portugython/rede.py +0 -0
  43. {portugython-0.3.0 → portugython-0.4.1}/portugython/registro.py +0 -0
  44. {portugython-0.3.0 → portugython-0.4.1}/portugython/serializacao.py +0 -0
  45. {portugython-0.3.0 → portugython-0.4.1}/portugython/sistema.py +0 -0
  46. {portugython-0.3.0 → portugython-0.4.1}/portugython/soquete.py +0 -0
  47. {portugython-0.3.0 → portugython-0.4.1}/portugython/subprocesso.py +0 -0
  48. {portugython-0.3.0 → portugython-0.4.1}/portugython/tempo.py +0 -0
  49. {portugython-0.3.0 → portugython-0.4.1}/portugython/threads.py +0 -0
  50. {portugython-0.3.0 → portugython-0.4.1}/portugython/tipagem.py +0 -0
  51. {portugython-0.3.0 → portugython-0.4.1}/tests/__init__.py +0 -0
  52. {portugython-0.3.0 → portugython-0.4.1}/tests/test_importador.py +0 -0
  53. {portugython-0.3.0 → portugython-0.4.1}/tests/test_submodulos.py +0 -0
@@ -0,0 +1,151 @@
1
+ # Changelog
2
+
3
+ ## 0.4.1 (2026-06-26)
4
+
5
+ Corrige acentuação em toda a documentação (README, CHANGELOG, docstrings).
6
+ Sem alterações na API ou no código.
7
+
8
+
9
+
10
+ Adiciona módulo `transpilador`: transpilador de código-fonte baseado no tokenizador do
11
+ Python que traduz palavras-chave para português, permitindo sintaxe Python completamente
12
+ em português.
13
+
14
+ Novo módulo `portugython.transpilador`:
15
+
16
+ - `traduzir(codigo)` - traduz código Python em português para Python padrão
17
+ - `traduzir_para_portugues(codigo)` - tradução inversa
18
+ - `executar_texto(codigo)` - traduz e executa uma string de código em português
19
+ - `executar_arquivo(caminho)` - traduz e executa um arquivo `.ptpy`
20
+ - `mostrar_traducao(codigo)` - imprime o código Python equivalente
21
+ - `MAPA_PALAVRAS_CHAVE` - tabela completa de tradução de palavras-chave
22
+ - `PALAVRAS_RESERVADAS` - frozenset de palavras-chave reservadas em português
23
+
24
+ Traduções de palavras-chave (34 palavras):
25
+
26
+ se -> if senaose -> elif senao -> else
27
+ para -> for enquanto -> while parar -> break
28
+ continuar -> continue passar -> pass
29
+ defina -> def classe -> class retorne -> return
30
+ produzca -> yield anonima -> lambda
31
+ importe -> import de -> from como -> as
32
+ tente -> try exceto -> except finalmente -> finally
33
+ levante -> raise com -> with
34
+ nao -> not e -> and ou -> or
35
+ em -> in eh -> is
36
+ excluir -> del afirmar -> assert
37
+ global -> global naolocal -> nonlocal
38
+ assincronico -> async aguardar -> await
39
+ Verdadeiro -> True Falso -> False Nenhum -> None
40
+
41
+ Novo ponto de entrada CLI: `ptpy` executa arquivos `.ptpy` diretamente:
42
+
43
+ ptpy meu_programa.ptpy
44
+ ptpy -c 'para i em intervalo(3): escreva(i)'
45
+ ptpy --mostrar meu_programa.ptpy # exibe o Python equivalente
46
+
47
+ Hook de importação estendido para carregar arquivos `.ptpy` pelo sistema de importação normal.
48
+
49
+ Exemplo de programa `.ptpy`:
50
+
51
+ ```python
52
+ defina fatorial(n):
53
+ se n <= 1:
54
+ retorne 1
55
+ senao:
56
+ retorne n * fatorial(n - 1)
57
+
58
+ para i em intervalo(1, 6):
59
+ escreva(f"{i}! = {fatorial(i)}")
60
+ ```
61
+
62
+ ## 0.3.0 (2026-06-26)
63
+
64
+ Adiciona hook de importação para que todos os módulos em português funcionem como
65
+ importações de nível superior.
66
+
67
+ Após `import portugython`, a sintaxe completa em nível de stdlib funciona:
68
+
69
+ import aleatorio
70
+ from matematica import raiz_quadrada, PI
71
+ from colecoes import Contador, Pilha, Fila
72
+ from tempo import agora, hoje
73
+ from expressao import buscar, encontrar_todos
74
+ from dados import serializar, deserializar # json
75
+ from subprocesso import executar
76
+ from caminho import Caminho
77
+ # ... todos os 36 módulos
78
+
79
+ Novos exports:
80
+ - `portugython.instalar()` - instala o gancho (chamado automaticamente)
81
+ - `portugython.desinstalar()` - remove o gancho
82
+ - `portugython.listar_modulos()` - retorna o mapa de nomes
83
+
84
+ ## 0.2.0 (2026-06-26)
85
+
86
+ Cobertura completa da stdlib. 36 submódulos no total, todos importáveis via
87
+ `from portugython import <modulo>`:
88
+
89
+ **Novos em 0.2.0:**
90
+ - `caminho` (pathlib): Caminho com existe, eh_arquivo, listar, ler_texto, escrever_texto, etc.
91
+ - `json`: serializar, deserializar, serializar_arquivo, deserializar_arquivo
92
+ - `estatistica` (statistics): media, mediana, moda, desvio_padrao, covariancia, correlacao, quantis
93
+ - `enumeracao` (enum): Enumeracao, EnumeracaoInteira, EnumeracaoBandeira, automatico, unico
94
+ - `classe_dados` (dataclasses): classe_dados, campo, para_dicionario, para_tupla, substituir
95
+ - `contexto` (contextlib): gerenciador, suprimir, fechar_ao_sair, pilha_saida
96
+ - `tipagem` (typing): re-exporta todos os tipos com nomes em português
97
+ - `csv_pt` (csv): ler_csv, escrever_csv, LeitorCSV, EscritorCSV, LeitorDicionario
98
+ - `registro` (logging): obter_registrador, configurar_registro, depurar, informar, avisar, erro
99
+ - `argumentos` (argparse): AnalisadorArgumentos com adicionar_argumento, analisar
100
+ - `subprocesso` (subprocess): executar, executar_shell, saida, chamar
101
+ - `copia` (copy): copiar, copiar_profundo
102
+ - `hash_pt` (hashlib + hmac): md5, sha256, sha512, blake2b, codigo_autenticacao, comparar_seguro
103
+ - `threads` (threading): Thread, Semaforo, Evento, Trava, contagem_threads, thread_atual
104
+ - `abstrato` (abc): ClasseAbstrata, metodo_abstrato, propriedade_abstrata
105
+ - `bisecao` (bisect + heapq): inserir_ordenado, buscar_ordenado, heapificar, empurrar, n_maiores
106
+ - `identificador` (uuid): uuid1, uuid3, uuid4, uuid5
107
+ - `calendario` (calendar): dias_no_mes, eh_ano_bissexto, dia_semana, calendario_mes
108
+ - `configuracao` (configparser): AnalisadorConfig com ler_arquivo, obter, definir, escrever_arquivo
109
+ - `serializacao` (pickle): serializar, deserializar, serializar_arquivo, deserializar_arquivo
110
+ - `codificacao` (base64 + codecs): para_base64, de_base64, para_base32, para_base16
111
+ - `compressao` (gzip + zlib): comprimir_gzip, descomprimir_gzip, comprimir_zlib
112
+ - `formatacao` (textwrap + pprint + string): quebrar, preencher, dedenter, recuar, imprimir_bonito
113
+ - `depuracao` (traceback + warnings + gc): imprimir_excecao, formatar_excecao, coletar_lixo
114
+ - `soquete` (socket): Soquete, criar_conexao, criar_servidor, nome_host, endereco_ip
115
+ - `assincronico` (asyncio): executar, criar_tarefa, dormir, reunir, Evento, Fila
116
+ - `estrutura` (struct): empacotar, desempacotar, calcular_tamanho
117
+ - `rede` (urllib + http): baixar_url, abrir_url, analisar_url, codificar_url, codificar_parametros
118
+
119
+ Também em 0.2.0:
120
+ - Correção: alias de builtin `identificador` renomeado para `obter_id` para evitar shadowing do submódulo uuid
121
+ - 49 testes cobrindo todos os módulos
122
+
123
+ ## 0.1.0 (2026-06-26)
124
+
125
+ - Adiciona conjunto completo de submódulos da stdlib com traduções em português:
126
+ - `aleatorio` (random): escolha, embaralhe, amostra, gauss, normal, etc.
127
+ - `matematica` (math): raiz_quadrada, seno, cosseno, fatorial, mdc, mmc, etc.
128
+ - `sistema` (os + sys): diretorio_atual, listar_diretorio, existe, sair, etc.
129
+ - `tempo` (time + datetime): Data, Hora, DataHora, Duracao, agora, hoje, dormir, etc.
130
+ - `colecoes` (collections): Contador, Deque, DicionarioOrdenado, Pilha, Fila, etc.
131
+ - `iteradores` (itertools): encadeie, combine, permute, acumule, agrupe, etc.
132
+ - `funcional` (functools): reduzido, parcial, cache, compor, negado, etc.
133
+ - `expressao` (re): compilar, buscar, substituir, encontrar_todos, Padrao, etc.
134
+ - Reescrita do `__init__.py` com nomes em português limpos (remove sufixos `_pt`)
135
+ - Adiciona classe `Conjunto` com métodos em português
136
+ - Expande `Texto`, `Lista`, `Dicionario` com mais métodos
137
+ - Adiciona mais tipos de exceção: ErroArquivo, ErroPermissao, ErroRecursao, ErroPausa
138
+ - Versão mínima do Python elevada para >=3.10
139
+ - 30 testes cobrindo todos os módulos
140
+
141
+ ## 0.0.15 (2026-06-26)
142
+
143
+ - Adiciona traduções em português dos builtins e funções principais do Python
144
+ - Introduz classes Lista, Dicionario, Texto com métodos em português
145
+ - Adiciona funções auxiliares: se(), para_cada(), filtro()
146
+ - Adiciona classes de exceção em português
147
+ - Expande a suíte de testes
148
+
149
+ ## 0.0.14 (2022-11-28)
150
+
151
+ - Última versão anterior no PyPI.
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: portugython
3
- Version: 0.3.0
4
- Summary: A Portuguese translation of the Python functions/modules/packages
3
+ Version: 0.4.1
4
+ Summary: A Portuguese translation of Python: functions, modules and syntax
5
5
  Project-URL: Homepage, https://github.com/spacemany2k38/portugython
6
6
  Project-URL: Bug Tracker, https://github.com/spacemany2k38/portugython/issues
7
7
  Author: Victor Kolis
@@ -31,22 +31,22 @@ Description-Content-Type: text/markdown
31
31
  [![Python versions](https://img.shields.io/pypi/pyversions/portugython.svg)](https://pypi.org/project/portugython/)
32
32
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
33
33
 
34
- Escreva Python em Portugues. Portugython traduz funcoes, tipos e modulos da biblioteca padrao do Python para nomes em portugues.
34
+ Escreva Python em Português. Portugython traduz funções, tipos e módulos da biblioteca padrão do Python para nomes em português.
35
35
 
36
- ## Instalacao
36
+ ## Instalação
37
37
 
38
38
  ```bash
39
39
  pip install portugython
40
40
  ```
41
41
 
42
- ## Uso basico
42
+ ## Uso básico
43
43
 
44
44
  ```python
45
45
  from portugython import *
46
46
 
47
- escreva("Ola, Mundo!")
48
- nome = leia("Qual e seu nome? ")
49
- escreva("Ola,", nome)
47
+ escreva("Olá, Mundo!")
48
+ nome = leia("Qual é seu nome? ")
49
+ escreva("Olá,", nome)
50
50
 
51
51
  numeros = Lista([1, 2, 3, 4, 5])
52
52
  numeros.adicione(6)
@@ -60,9 +60,9 @@ resultado = se(tamanho(pares) > 0, "tem pares", "sem pares")
60
60
  escreva(resultado)
61
61
  ```
62
62
 
63
- ## Modulos da biblioteca padrao
63
+ ## Módulos da biblioteca padrão
64
64
 
65
- Cada modulo da stdlib tem uma versao em portugues que pode ser importada separadamente.
65
+ Cada módulo da stdlib tem uma versão em português que pode ser importada separadamente.
66
66
 
67
67
  ### aleatorio (random)
68
68
 
@@ -159,7 +159,7 @@ print(p.x, p.y)
159
159
  ```python
160
160
  from portugython import iteradores
161
161
 
162
- # Combinatoria
162
+ # Combinatória
163
163
  for combo in iteradores.combine([1, 2, 3, 4], 2):
164
164
  print(combo)
165
165
 
@@ -167,7 +167,7 @@ for combo in iteradores.combine([1, 2, 3, 4], 2):
167
167
  for par in iteradores.produto("AB", "12"):
168
168
  print(par)
169
169
 
170
- # Acumulacao
170
+ # Acumulação
171
171
  totais = list(iteradores.acumule([1, 2, 3, 4, 5]))
172
172
 
173
173
  # Encadeamento
@@ -179,21 +179,21 @@ unido = list(iteradores.encadeie([1, 2], [3, 4], [5]))
179
179
  ```python
180
180
  from portugython import funcional
181
181
 
182
- # Reducao
182
+ # Redução
183
183
  total = funcional.reduzido(lambda a, b: a + b, range(1, 11))
184
184
 
185
- # Funcao parcial
185
+ # Função parcial
186
186
  multiplicar_por_3 = funcional.parcial(lambda a, b: a * b, 3)
187
187
  print(multiplicar_por_3(7))
188
188
 
189
- # Memoizacao
189
+ # Memoização
190
190
  @funcional.cache
191
191
  def fibonacci(n):
192
192
  if n < 2:
193
193
  return n
194
194
  return fibonacci(n - 1) + fibonacci(n - 2)
195
195
 
196
- # Composicao
196
+ # Composição
197
197
  dobrar = lambda x: x * 2
198
198
  somar_um = lambda x: x + 1
199
199
  dobrar_e_somar = funcional.compor(somar_um, dobrar)
@@ -213,26 +213,26 @@ if m:
213
213
  # Todos os resultados
214
214
  numeros = expressao.encontrar_todos(r"\d+", "1 mais 2 igual 3")
215
215
 
216
- # Substituicao
216
+ # Substituição
217
217
  limpo = expressao.substituir(r"\s+", " ", "texto com espacos")
218
218
 
219
- # Padrao reutilizavel
219
+ # Padrão reutilizável
220
220
  email = expressao.Padrao(r"[\w.+-]+@[\w-]+\.[a-z]{2,}")
221
221
  if email.encontrar("contato@example.com"):
222
- print("Email valido")
222
+ print("E-mail válido")
223
223
  ```
224
224
 
225
- ## Referencia de builtins
225
+ ## Referência de builtins
226
226
 
227
- ### Entrada / Saida
228
- | Portugues | Python |
227
+ ### Entrada / Saída
228
+ | Português | Python |
229
229
  |-----------|--------|
230
230
  | `escreva` | `print` |
231
231
  | `leia` | `input` |
232
232
  | `abra` | `open` |
233
233
 
234
234
  ### Tipos
235
- | Portugues | Python |
235
+ | Português | Python |
236
236
  |-----------|--------|
237
237
  | `inteiro` | `int` |
238
238
  | `texto` | `str` |
@@ -245,14 +245,14 @@ if email.encontrar("contato@example.com"):
245
245
  | `intervalo` | `range` |
246
246
 
247
247
  ### Constantes
248
- | Portugues | Python |
248
+ | Português | Python |
249
249
  |-----------|--------|
250
250
  | `Verdadeiro` | `True` |
251
251
  | `Falso` | `False` |
252
252
  | `Nenhum` | `None` |
253
253
 
254
- ### Funcoes de sequencia
255
- | Portugues | Python |
254
+ ### Funções de sequência
255
+ | Português | Python |
256
256
  |-----------|--------|
257
257
  | `tamanho` | `len` |
258
258
  | `soma` | `sum` |
@@ -266,27 +266,130 @@ if email.encontrar("contato@example.com"):
266
266
  | `mapeado` | `map` |
267
267
  | `filtrado` | `filter` |
268
268
 
269
- ### Operadores logicos
270
- | Portugues | Python |
269
+ ### Operadores lógicos
270
+ | Português | Python |
271
271
  |-----------|--------|
272
272
  | `nao(x)` | `not x` |
273
273
  | `e(a, b)` | `a and b` |
274
274
  | `ou(a, b)` | `a or b` |
275
275
 
276
- ### Funcoes utilitarias
277
- | Portugues | Python |
276
+ ### Funções utilitárias
277
+ | Português | Python |
278
278
  |-----------|--------|
279
279
  | `se(c, a, b)` | `a if c else b` |
280
280
  | `para_cada(f, it)` | `list(map(f, it))` |
281
281
  | `filtro(f, it)` | `list(filter(f, it))` |
282
282
  | `reduzido(f, it)` | `functools.reduce(f, it)` |
283
283
 
284
+ ## Transpilador de palavras-chave
285
+
286
+ Portugython inclui um transpilador completo que traduz a sintaxe do Python
287
+ (palavras-chave) para português. Isso permite escrever programas Python
288
+ inteiramente em português.
289
+
290
+ ### CLI: ptpy
291
+
292
+ ```bash
293
+ ptpy meu_programa.ptpy # executa um arquivo .ptpy
294
+ ptpy -c 'para i em intervalo(3): escreva(i)' # executa inline
295
+ ptpy --mostrar meu_programa.ptpy # imprime o Python equivalente
296
+ ```
297
+
298
+ ### API Python
299
+
300
+ ```python
301
+ from portugython import traduzir, executar_texto, executar_arquivo
302
+
303
+ # Traduzir uma string
304
+ codigo_pt = """
305
+ defina fatorial(n):
306
+ se n <= 1:
307
+ retorne 1
308
+ senao:
309
+ retorne n * fatorial(n - 1)
310
+ """
311
+ print(traduzir(codigo_pt))
312
+ # def fatorial(n):
313
+ # if n <= 1:
314
+ # return 1
315
+ # else:
316
+ # return n * fatorial(n - 1)
317
+
318
+ # Executar diretamente
319
+ executar_texto("para i em intervalo(3):\n escreva(i)")
320
+
321
+ # Executar um arquivo .ptpy
322
+ executar_arquivo("meu_programa.ptpy")
323
+ ```
324
+
325
+ ### Programa completo em português (.ptpy)
326
+
327
+ ```python
328
+ # fatorial.ptpy
329
+ importe portugython
330
+
331
+ defina fatorial(n):
332
+ se n <= 1:
333
+ retorne 1
334
+ senao:
335
+ retorne n * fatorial(n - 1)
336
+
337
+ defina verificar_primo(n):
338
+ se n < 2:
339
+ retorne Falso
340
+ para i em intervalo(2, n):
341
+ se n % i == 0:
342
+ retorne Falso
343
+ retorne Verdadeiro
344
+
345
+ primos = [x para x em intervalo(2, 20) se verificar_primo(x)]
346
+ escreva("Primos:", primos)
347
+
348
+ para n em intervalo(1, 8):
349
+ escreva(f"{n}! = {fatorial(n)}")
350
+
351
+ tente:
352
+ resultado = 10 / 0
353
+ exceto ZeroDivisionError como err:
354
+ escreva("Erro capturado:", err)
355
+ finalmente:
356
+ escreva("Pronto!")
357
+ ```
358
+
359
+ ### Tabela de palavras-chave
360
+
361
+ | Português | Python | | Português | Python |
362
+ |-----------|--------|-|-----------|--------|
363
+ | `se` | `if` | | `senao` | `else` |
364
+ | `senaose` | `elif` | | `para` | `for` |
365
+ | `enquanto` | `while` | | `parar` | `break` |
366
+ | `continuar` | `continue` | | `passar` | `pass` |
367
+ | `defina` | `def` | | `classe` | `class` |
368
+ | `retorne` | `return` | | `produzca` | `yield` |
369
+ | `anonima` | `lambda` | | `importe` | `import` |
370
+ | `de` | `from` | | `como` | `as` |
371
+ | `tente` | `try` | | `exceto` | `except` |
372
+ | `finalmente` | `finally` | | `levante` | `raise` |
373
+ | `com` | `with` | | `nao` | `not` |
374
+ | `e` | `and` | | `ou` | `or` |
375
+ | `em` | `in` | | `eh` | `is` |
376
+ | `excluir` | `del` | | `afirmar` | `assert` |
377
+ | `global` | `global` | | `naolocal` | `nonlocal` |
378
+ | `assincronico` | `async` | | `aguardar` | `await` |
379
+ | `Verdadeiro` | `True` | | `Falso` | `False` |
380
+ | `Nenhum` | `None` | | | |
381
+
382
+ > **Nota**: Palavras como `e`, `ou`, `de`, `com` e `em` são palavras-chave
383
+ > reservadas no contexto de arquivos `.ptpy`. Evite usá-las como nomes de
384
+ > variáveis nesses arquivos, assim como não se usa `if` ou `for` como
385
+ > variáveis em Python normal.
386
+
284
387
  ## Contribuir
285
388
 
286
- 1. Crie um fork deste repositorio
389
+ 1. Crie um fork deste repositório
287
390
  2. Crie uma branch nova a partir de main
288
391
  3. Envie um pull request
289
392
 
290
- ## Licenca
393
+ ## Licença
291
394
 
292
395
  MIT
@@ -4,22 +4,22 @@
4
4
  [![Python versions](https://img.shields.io/pypi/pyversions/portugython.svg)](https://pypi.org/project/portugython/)
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
6
 
7
- Escreva Python em Portugues. Portugython traduz funcoes, tipos e modulos da biblioteca padrao do Python para nomes em portugues.
7
+ Escreva Python em Português. Portugython traduz funções, tipos e módulos da biblioteca padrão do Python para nomes em português.
8
8
 
9
- ## Instalacao
9
+ ## Instalação
10
10
 
11
11
  ```bash
12
12
  pip install portugython
13
13
  ```
14
14
 
15
- ## Uso basico
15
+ ## Uso básico
16
16
 
17
17
  ```python
18
18
  from portugython import *
19
19
 
20
- escreva("Ola, Mundo!")
21
- nome = leia("Qual e seu nome? ")
22
- escreva("Ola,", nome)
20
+ escreva("Olá, Mundo!")
21
+ nome = leia("Qual é seu nome? ")
22
+ escreva("Olá,", nome)
23
23
 
24
24
  numeros = Lista([1, 2, 3, 4, 5])
25
25
  numeros.adicione(6)
@@ -33,9 +33,9 @@ resultado = se(tamanho(pares) > 0, "tem pares", "sem pares")
33
33
  escreva(resultado)
34
34
  ```
35
35
 
36
- ## Modulos da biblioteca padrao
36
+ ## Módulos da biblioteca padrão
37
37
 
38
- Cada modulo da stdlib tem uma versao em portugues que pode ser importada separadamente.
38
+ Cada módulo da stdlib tem uma versão em português que pode ser importada separadamente.
39
39
 
40
40
  ### aleatorio (random)
41
41
 
@@ -132,7 +132,7 @@ print(p.x, p.y)
132
132
  ```python
133
133
  from portugython import iteradores
134
134
 
135
- # Combinatoria
135
+ # Combinatória
136
136
  for combo in iteradores.combine([1, 2, 3, 4], 2):
137
137
  print(combo)
138
138
 
@@ -140,7 +140,7 @@ for combo in iteradores.combine([1, 2, 3, 4], 2):
140
140
  for par in iteradores.produto("AB", "12"):
141
141
  print(par)
142
142
 
143
- # Acumulacao
143
+ # Acumulação
144
144
  totais = list(iteradores.acumule([1, 2, 3, 4, 5]))
145
145
 
146
146
  # Encadeamento
@@ -152,21 +152,21 @@ unido = list(iteradores.encadeie([1, 2], [3, 4], [5]))
152
152
  ```python
153
153
  from portugython import funcional
154
154
 
155
- # Reducao
155
+ # Redução
156
156
  total = funcional.reduzido(lambda a, b: a + b, range(1, 11))
157
157
 
158
- # Funcao parcial
158
+ # Função parcial
159
159
  multiplicar_por_3 = funcional.parcial(lambda a, b: a * b, 3)
160
160
  print(multiplicar_por_3(7))
161
161
 
162
- # Memoizacao
162
+ # Memoização
163
163
  @funcional.cache
164
164
  def fibonacci(n):
165
165
  if n < 2:
166
166
  return n
167
167
  return fibonacci(n - 1) + fibonacci(n - 2)
168
168
 
169
- # Composicao
169
+ # Composição
170
170
  dobrar = lambda x: x * 2
171
171
  somar_um = lambda x: x + 1
172
172
  dobrar_e_somar = funcional.compor(somar_um, dobrar)
@@ -186,26 +186,26 @@ if m:
186
186
  # Todos os resultados
187
187
  numeros = expressao.encontrar_todos(r"\d+", "1 mais 2 igual 3")
188
188
 
189
- # Substituicao
189
+ # Substituição
190
190
  limpo = expressao.substituir(r"\s+", " ", "texto com espacos")
191
191
 
192
- # Padrao reutilizavel
192
+ # Padrão reutilizável
193
193
  email = expressao.Padrao(r"[\w.+-]+@[\w-]+\.[a-z]{2,}")
194
194
  if email.encontrar("contato@example.com"):
195
- print("Email valido")
195
+ print("E-mail válido")
196
196
  ```
197
197
 
198
- ## Referencia de builtins
198
+ ## Referência de builtins
199
199
 
200
- ### Entrada / Saida
201
- | Portugues | Python |
200
+ ### Entrada / Saída
201
+ | Português | Python |
202
202
  |-----------|--------|
203
203
  | `escreva` | `print` |
204
204
  | `leia` | `input` |
205
205
  | `abra` | `open` |
206
206
 
207
207
  ### Tipos
208
- | Portugues | Python |
208
+ | Português | Python |
209
209
  |-----------|--------|
210
210
  | `inteiro` | `int` |
211
211
  | `texto` | `str` |
@@ -218,14 +218,14 @@ if email.encontrar("contato@example.com"):
218
218
  | `intervalo` | `range` |
219
219
 
220
220
  ### Constantes
221
- | Portugues | Python |
221
+ | Português | Python |
222
222
  |-----------|--------|
223
223
  | `Verdadeiro` | `True` |
224
224
  | `Falso` | `False` |
225
225
  | `Nenhum` | `None` |
226
226
 
227
- ### Funcoes de sequencia
228
- | Portugues | Python |
227
+ ### Funções de sequência
228
+ | Português | Python |
229
229
  |-----------|--------|
230
230
  | `tamanho` | `len` |
231
231
  | `soma` | `sum` |
@@ -239,27 +239,130 @@ if email.encontrar("contato@example.com"):
239
239
  | `mapeado` | `map` |
240
240
  | `filtrado` | `filter` |
241
241
 
242
- ### Operadores logicos
243
- | Portugues | Python |
242
+ ### Operadores lógicos
243
+ | Português | Python |
244
244
  |-----------|--------|
245
245
  | `nao(x)` | `not x` |
246
246
  | `e(a, b)` | `a and b` |
247
247
  | `ou(a, b)` | `a or b` |
248
248
 
249
- ### Funcoes utilitarias
250
- | Portugues | Python |
249
+ ### Funções utilitárias
250
+ | Português | Python |
251
251
  |-----------|--------|
252
252
  | `se(c, a, b)` | `a if c else b` |
253
253
  | `para_cada(f, it)` | `list(map(f, it))` |
254
254
  | `filtro(f, it)` | `list(filter(f, it))` |
255
255
  | `reduzido(f, it)` | `functools.reduce(f, it)` |
256
256
 
257
+ ## Transpilador de palavras-chave
258
+
259
+ Portugython inclui um transpilador completo que traduz a sintaxe do Python
260
+ (palavras-chave) para português. Isso permite escrever programas Python
261
+ inteiramente em português.
262
+
263
+ ### CLI: ptpy
264
+
265
+ ```bash
266
+ ptpy meu_programa.ptpy # executa um arquivo .ptpy
267
+ ptpy -c 'para i em intervalo(3): escreva(i)' # executa inline
268
+ ptpy --mostrar meu_programa.ptpy # imprime o Python equivalente
269
+ ```
270
+
271
+ ### API Python
272
+
273
+ ```python
274
+ from portugython import traduzir, executar_texto, executar_arquivo
275
+
276
+ # Traduzir uma string
277
+ codigo_pt = """
278
+ defina fatorial(n):
279
+ se n <= 1:
280
+ retorne 1
281
+ senao:
282
+ retorne n * fatorial(n - 1)
283
+ """
284
+ print(traduzir(codigo_pt))
285
+ # def fatorial(n):
286
+ # if n <= 1:
287
+ # return 1
288
+ # else:
289
+ # return n * fatorial(n - 1)
290
+
291
+ # Executar diretamente
292
+ executar_texto("para i em intervalo(3):\n escreva(i)")
293
+
294
+ # Executar um arquivo .ptpy
295
+ executar_arquivo("meu_programa.ptpy")
296
+ ```
297
+
298
+ ### Programa completo em português (.ptpy)
299
+
300
+ ```python
301
+ # fatorial.ptpy
302
+ importe portugython
303
+
304
+ defina fatorial(n):
305
+ se n <= 1:
306
+ retorne 1
307
+ senao:
308
+ retorne n * fatorial(n - 1)
309
+
310
+ defina verificar_primo(n):
311
+ se n < 2:
312
+ retorne Falso
313
+ para i em intervalo(2, n):
314
+ se n % i == 0:
315
+ retorne Falso
316
+ retorne Verdadeiro
317
+
318
+ primos = [x para x em intervalo(2, 20) se verificar_primo(x)]
319
+ escreva("Primos:", primos)
320
+
321
+ para n em intervalo(1, 8):
322
+ escreva(f"{n}! = {fatorial(n)}")
323
+
324
+ tente:
325
+ resultado = 10 / 0
326
+ exceto ZeroDivisionError como err:
327
+ escreva("Erro capturado:", err)
328
+ finalmente:
329
+ escreva("Pronto!")
330
+ ```
331
+
332
+ ### Tabela de palavras-chave
333
+
334
+ | Português | Python | | Português | Python |
335
+ |-----------|--------|-|-----------|--------|
336
+ | `se` | `if` | | `senao` | `else` |
337
+ | `senaose` | `elif` | | `para` | `for` |
338
+ | `enquanto` | `while` | | `parar` | `break` |
339
+ | `continuar` | `continue` | | `passar` | `pass` |
340
+ | `defina` | `def` | | `classe` | `class` |
341
+ | `retorne` | `return` | | `produzca` | `yield` |
342
+ | `anonima` | `lambda` | | `importe` | `import` |
343
+ | `de` | `from` | | `como` | `as` |
344
+ | `tente` | `try` | | `exceto` | `except` |
345
+ | `finalmente` | `finally` | | `levante` | `raise` |
346
+ | `com` | `with` | | `nao` | `not` |
347
+ | `e` | `and` | | `ou` | `or` |
348
+ | `em` | `in` | | `eh` | `is` |
349
+ | `excluir` | `del` | | `afirmar` | `assert` |
350
+ | `global` | `global` | | `naolocal` | `nonlocal` |
351
+ | `assincronico` | `async` | | `aguardar` | `await` |
352
+ | `Verdadeiro` | `True` | | `Falso` | `False` |
353
+ | `Nenhum` | `None` | | | |
354
+
355
+ > **Nota**: Palavras como `e`, `ou`, `de`, `com` e `em` são palavras-chave
356
+ > reservadas no contexto de arquivos `.ptpy`. Evite usá-las como nomes de
357
+ > variáveis nesses arquivos, assim como não se usa `if` ou `for` como
358
+ > variáveis em Python normal.
359
+
257
360
  ## Contribuir
258
361
 
259
- 1. Crie um fork deste repositorio
362
+ 1. Crie um fork deste repositório
260
363
  2. Crie uma branch nova a partir de main
261
364
  3. Envie um pull request
262
365
 
263
- ## Licenca
366
+ ## Licença
264
367
 
265
368
  MIT