Create python dictionaries using lists

Asked

Viewed 1,263 times

2

I’m trying to create a translator that translates Portuguese words into binary code. I was able to do this to type only one word, but when I try to use 2 words, in the case "ab", nothing happens. I would like to know what remains to be put in place so that the programme also works 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[:]])
  • This representation is following the ASCII table, right? So there is no possibility of entering with accented characters? Or their codification must be taken into account?

  • I believe you need to concatenate the typed characters, have a question that teaches it here in the OS(At this link). Either that or merge what is typed into a list, and from that list you return to the dictionary and "translate" to binary.

1 answer

2

The if you are using:

if palavra[:] in dicionario:

Test whether the palavra writing exists in the dicionario as a whole, which is not what you want. The solution is to analyze letter to word and find the binary corresponding to the dicionario.

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

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

For each letra in palavra obtain the encoding with dicionario[letra] and join the string through join.

Creating the binaries

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

for x in range(255):
  dicionario[chr(x)] = "{:08b}".format(x)

The chr(x) the letter corresponding to the number in which the for goes, while the "{:08b}".format(x) creates the binary representation of this number with 8 digits by placing zeros as filler.

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)

Online example on Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.