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
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?
– Woss
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.
– Vitor Couto