Posts Tagged ‘ python

Google Translate Python no seu terminal

Meu interesse inicial era encontrar algum tradutor, inglês -> português, que rode via terminal. Não encontrei nada que me agradasse então resolvi fazer algo aqui.

O script em python pega a palavra que for digitada submet ao google translate e te mostra o resultado. Pra fazer isso usei o curl pra fazer a requisição fingindo ser o mozilla. Depois fiz um parser procurando uma tag span que tem o atributo title com valor igual a palavra passada ao google.

Pronto, bem simples e funciona.
A partir desse da pra fazer muita coisa…

esta disponível para todos http://bruno.tuy.com.br/desenv/translate.py

Girar Matriz com Python

Criar matriz:

>>> mat = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

Mostra normal:

>>> for lin in range(3):
    text = ”
    for col in range(3):
        text += ‘ ‘ + mat[lin][col]
    print text

Mostrar girada em 90 graus:

>>> for lin in range(3):
    text = ”
    for col in range(3):
        text += ‘ ‘ + mat[col][2 - lin]
    print text

Mostrar girada em 180 graus:

>>> for lin in range(3):
    text = ”
    for col in range(3):
        text += ‘ ‘ + mat[2 - lin][2 - col]
    print text

Mostrar girada em 270 graus:

>>> for lin in range(3):
    text = ”
    for col in range(3):
        text += ‘ ‘ + mat[2 - col][lin]
    print text

Python conectando com Postgres

>>> import psycopg2
>>> conexao = psycopg2.connect(“dbname=’nome_base’ user=’usuario_base’ host=’endereco_da_base ou IP’ password=’senha_da_base’”);
>>> cursor = conexao.cursor()
>>> cursor.execute(“SELECT * FROM tabela”)
>>> resposta = cursor.fetchall()
>>> print resposta

>>> for linha in resposta:
>>>     print linha
>>> conexao.close()

Python + xml.dom – Editar um xml

Ler e editar um xml Existente

Carregar o objeto.

>>> xml0 = xml.dom.minidom.parse(“c:\\teste\\novo.xml”)

Imprima na tela para ver se foi carregado mesmo e verifique o conteudo

>>> print xml0.toxml()
<?xml version=”1.0″ ?><usuarios><user id=”1″ login=”bruno-tuy”>Bruno Tuy</user><user id=”2″ login=”bruno.reis”>Bruno Reis</user><user id=”3″ login=”lucas.mendes”>Lucas Mendes</user><user id=”4″ login=”bruno”>_Bruno_</user></usuarios>

Aqui ele retornou desse jeito ai, sem quebra de linha e indentação, é a maneira ideal de salvar o xml pois assim o programa trabalha com ele perfeitamente bem, se o seu retornou um xml com quebras de linhas e indentação vai acontecer o seguinte, o python vai entender que o enter(\n) são filhos também, ai você vai ter que tratar isso.

Agora vamos ler os atributos da primeira tag do xml.

>>> print “Id: ” + xml0.firstChild.childNodes[0].getAttribute(“id”)
Id: 1
>>> print “Login: ” + xml0.firstChild.childNodes[0].getAttribute(“login”)
Login: bruno-tuy
>>> print “Nome: ” + xml0.firstChild.childNodes[0].firstChild.data
Nome: Bruno Tuy

Imprimir o atributo login da tag de id 2

>>> for filho in xml0.firstChild.getElementsByTagName(“user”):
if (filho.getAttribute(“id”) == “2″):
print filho.getAttribute(“login”)

bruno.reis

– getElementsByTagName(“user”) pode ser substituido por childNodes

Apagar alguma tag

>>> xml0.firstChild.removeChild( xml0.firstChild.childNodes[2] )
<DOM Element: user at 0×23c16c0>
>>> print xml0.toxml()
<?xml version=”1.0″ ?><usuarios><user id=”1″ login=”bruno-tuy”>Bruno Tuy</user><user id=”2″ login=”bruno.reis”>Bruno Reis</user><user id=”4″ login=”bruno”>_Bruno_</user></usuarios>

– Repare que o usuario com id 3 foi removido

Mudar atributos de uma tag

>>> xml0.firstChild.childNodes[0].setAttribute(“login”, “bruno.tuy”)
>>> print xml0.toxml()

<?xml version=”1.0″ ?><usuarios><user id=”1″ login=”bruno.tuy”>Bruno Tuy</user><user id=”2″ login=”bruno.reis”>Bruno Reis</user><user id=”4″ login=”bruno”>_Bruno_</user></usuarios>

– Veja que o atributo login da tag com id 1 foi alterado.

Mudar texto contido entre as tags

>>> xml0.firstChild.childNodes[2].firstChild.nodeValue = “Bruno”
>>> print xml0.toxml()
<?xml version=”1.0″ ?><usuarios><user id=”1″ login=”bruno.tuy”>Bruno Tuy</user><user id=”2″ login=”bruno.reis”>Bruno Reis</user><user id=”4″ login=”bruno”>Bruno</user></usuarios>

salvar tudo

>>> arq = file(“c:\\teste\\novo.xml”, “w”)
>>> xml0.writexml(arq)
>>> arq.close()

Criar xml com Python + xml.dom

Post rapido para salvar algo que fiz hoje e preciso lembrar durante um bom tempo. Trabalhando com XML usando python.

Criando um XML.

>>> NewXml = xml.dom.minidom.Document()

Criando o elementos root do XML(TAGS).

>>> tag = NewXml.createElement(“lista”)
>>> NewXml.appendChild(tag)

Criando elementos do XML(TAGS).

>>> tag = NewXml.createElement(“usuario”)

Criando atributos

>>> tag.setAttribute(“login”, “burno.tuy”)
>>> tag.setAttribute(“senha”, “123456″)

Colocar um texto entre as tags.

>>> texto = NewXml.createTextNode(“Bruno Tuy”)
>>> tag.appendChild(texto)

Agora colocar o elemento criado no XML

>>> NewXml.firstChild.appendChild(tag)

Só pra confirmar é bom imprimir o xml

>>> print NewXml.toxml()

Agora vamos salvar

>>> arq = file(“c:\\teste\\novo.xml”, “w”)
>>> NewXml.writexml(arq)
>>> arq.close()

O arquivo já vai aparecer la salvo, mais meio complicado pra leitura, se quiser deixar ele mais legível pode usar alguns parâmetros no write. Exemplo:

>>> NewXml.writexml(arq, ” “, ” “, “\n”, “UTF-8″)

- Primeiro argumento o arquivo
- Segundo a indentação inicial.
- Terceiro a indentação adicional.
- Quarto argumento o que vai ser usado no final da tag.
- Quinto a codificação