Create dictionaries in python using lists

2

I'm trying to create a translator that translates Portuguese words into binary code. I have already been able to do this to type only one word, but when I try to use 2 words, in case "ab", nothing happens. I would like to know what is missing so that the program can also work with words.

dicionario = {'a': '01100001', 'b' : '01100010'}
palavra = str(input('Digite a palavra que deseja traduzir para código binário:'))
if palavra[:] in dicionario:
        print(dicionario[palavra[:]])
    
asked by anonymous 22.09.2017 / 01:00

1 answer

2

O% w_that you are using:

if palavra[:] in dicionario:

Tests whether% written% exists in if as a whole, which is not what you want. The solution is to analyze letter by letter of the word and get the binary corresponding to palavra .

Assuming you have the encoding for all letters you can do this:

traduzido = ''.join(dicionario[letra] for letra in palavra)

For each dicionario in dicionario get the coding with letra and join palavra through dicionario[letra] .

Creating binaries

However with just two encoded characters the previous code would not work for real text. One solution is to generate the encoding for the various characters that exist in the ASCII table:

for x in range(255):
  dicionario[chr(x)] = "{:08b}".format(x)
The string gets the caratere corresponding to the number where join goes, whereas chr(x) creates the binary representation of that 8-digit number by putting zeros as a padding.

Putting it all together:

dicionario = {} #agora vazio pois são gerados
palavra = str(input('Digite a palavra que deseja traduzir para código binário:'))

#este for gera os carateres de 0 a 255 que correspondem a tabela ASCII
for x in range(255):
  dicionario[chr(x)] = "{:08b}".format(x)

traduzido = ''.join(dicionario[letra] for letra in palavra)
print("Tradução em binário: ", traduzido)

Ideone online sample

    
22.09.2017 / 04:05