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