2

I'm currently writing an ascii-binary/binary-ascii converter in Python for a school project, and I have an issue with converting from ascii (String text) to binary. The idea is to print the outcome in the test() on the bottom of the code.

When running the code in WingIDE, an error occurs: On the line starting with

bnary = bnary + binary[chnk]

KeyError: "Norway stun Poland 30:28 and spoil Bielecki's birthday party."

What I'm trying to do here is to convert the String of text stored in "text.txt" to a String of integers, and then print this binary string.

Any help is greatly appreciated. I tried looking at other ascii-binary vice-versa convertion related questions, but none seemed to work for me.

My code:

def code():    
    binary = {}
    ascii = {}

    # Generate ascii code
    for i in range(0,128) :
        ascii[format(i,'08b')] = chr(i)


    # Reverse the ascii code, this will be binary
    for k, v in ascii.iteritems():
        binary[v] = binary.get(v, [])
        binary[v].append(k)   

    return ascii

def encode(text,binary):
    '''
    Encode some text using text from a source
    '''
    bnary = ""

    fi = open(text, mode='rb')
    while True:
        chnk = fi.read()
        if chnk == '':
            break
        if chnk != '\n':

            binry = ""

            bnary = bnary + binary[chnk]

        return bnary

def decode(sourcecode,n, ascii):
    '''
    Decode a sourcecode using chunks of size n
    '''

    sentence = ""    

    f = open(sourcecode, mode='rb') # Open a file with filename <sourcecode>
    while True:
        chunk = f.read(n)           # Read n characters at time from an open file
        if chunk == '':             # This is one way to check for the End Of File in Python 
            break
        if chunk != '\n':

            setence = ""            # The ascii sentence generated

            # create a sentence
            sentence = sentence + ascii[chunk]

    return sentence

def test():
    '''
    A placeholder for some test cases.
    It is recommended that you use some existing framework, like unittest,
    but for a temporary testing in a development version can be done 
    directly in the module.
    '''

    print encode('text.txt', code())
    print decode('sourcecode.txt', 8, code())

test()
Winston Smith
  • 131
  • 1
  • 4
  • 11
  • FYI, "Norway stun Poland 30:28 and spoil Bielecki's birthday party." is the content of "text.txt". – Winston Smith Jun 02 '16 at 11:22
  • 3
    Please be more specific as to what converting between ASCII and binary means. Do you mean converting an integer, stored in binary, to its ASCII representation, and back? If so, in what base in the ASCII: binary, decimal, or other? If not that, just what do you mean? (I ask this before reading your code, since these questions are fundamental to judging your code.) – Rory Daulton Jun 02 '16 at 11:25
  • Is it intentional that you've got `binary`, `bnary` and `binry` in your `encode` method? – Joachim Sauer Jun 02 '16 at 11:39
  • Yeah, it is based it on the `def decode()` method, which has `sentence`, `setence`. – Winston Smith Jun 02 '16 at 11:41
  • What Python is that? 2.7 or 3.X? – Paul Jun 02 '16 at 12:04
  • I'm using Python 2.7 – Winston Smith Jun 02 '16 at 12:11

3 Answers3

4

If you want to decode and encode, have this solutions

Encode ascii to bin

def toBinary(string):
    return "".join([format(ord(char),'#010b')[2:] for char in string])

Encode bin to ascii

def toString(binaryString):
    return "".join([chr(int(binaryString[i:i+8],2)) for i in range(0,len(binaryString),8)])
  • 1
    Thanks, that worked like a charm! Greatly appreciated. – Winston Smith Jun 02 '16 at 12:21
  • @MortenAmundsen: In addition to accepting the most helpful answer (which you did), you should also upvote all good answers, including of course the accepted one. That is the full way to show appreciation here. – Rory Daulton Jun 02 '16 at 12:58
1

fi.read() returns the whole document the first time and '' next times. So you should do

text = fi.read()
for char in text:
     do_stuff()

Edit1

You can only read your file once. Thus you have to get your chars one by one. A file.read returns a string containing the whole document.

You can iterate over a string to get chars one by one.

The main error is your binary is {"a":['010001110'], "b":...} and you try to access with the key "azerty" where you should do it char by char:

string = "azer"
result = []
for c in string:
    result += binary[c]

 >>> result = [['11001'],[1001101'],...]
Paul
  • 315
  • 1
  • 9
  • Tried your suggestion: `def encode(text,binary): bnary = "" fi = open(text, mode='rb') while True: text = fi.read() for char in text: binry = "" bnary = bnary + binary[text] return bnary` I still get the same error as before; "KeyError: "Norway stun Poland 30:28(...)" – Winston Smith Jun 02 '16 at 11:44
  • You have more errors than that in your program but let's go step by step. – Paul Jun 02 '16 at 12:01
0
# Lets say your filename is stored in fname

def binary(n):
    return '{0:08b}'.format(n)

with open(fname) as f:
    content = f.readlines()
    for i in content:
        print(binary(ord(i)), end='')
    print('')

This will give you the integer value(from ascii) of each character in the file, line by line

Akash Lodha
  • 100
  • 9
  • Check this link for the format(n) part : http://stackoverflow.com/questions/10411085/converting-integer-to-binary-in-python – Akash Lodha Jun 02 '16 at 12:16
  • or create your own binary function that takes in an integer as input and returns the binary equivalnet of it. – Akash Lodha Jun 02 '16 at 12:18