Search code examples
pythoncompiler-constructionprogramming-languages

Generating a python file


I'm havin issues with python (Sorry for my personal feelings before.. :P).

I have a txt file, it contains a custom language and I have to translate it to a working python code.

The input:

import sys  

n = int(sys.argv[1]) ;;print "Beginning of the program!"

LOOP i in range(1,n) {print "The number:";;print i}

BRANCH n < 5 {print n ;;print "less than 5"}  

The wanted output looks exactly like this:

import sys  

n = int(sys.argv[1])   
print "Beginning of the program!"

for i in range(1,n) :  
    print "The number:"  
    print i  

if n < 5 :  
    print n   
    print "less than 5"    

The name of the input file is read from parameter. The out file is out.py. In case of a wrong parameter, it gives an error message. The ;; means a new line.

When I tried to do it, I made an array, I read all the lines into it, split by " ". Then I wanted to strip it from the marks I don't need. I made 2 loops, one for the lines, one for the words. So then I started to replace the things. Everything went fine until it came to the } mark. It finds it, but it can not replace or strip it. I have no more idea what to do.

My code (it's messy and I don't have the write to file at the moment):

f = open('test.txt', 'r')
#g = open('out.py', 'w')
allWords = map(lambda l: l.split(" "), f.readlines())
for i in range(len(allWords)):
    vanfor = -1
    vanif = -1
    for j in range(len(allWords[i])):
        a=allWords[i][j]
        a=a.replace(";;","\n")
        a=a.replace("CIKLUS","for")
        a=a.replace("ELAGAZAS","if")
        if a == "for":
            allWords[i][j+3] = str(allWords[i][j+3])+" :\n"
        if a == "if":
            allWords[i][j+3] = str(allWords[i][j+3])+" :\n"
        zarojel=a.find('}')
        if zarojel>-1:
            a=a.rstrip('}')
        a=a.replace("}","")
        a=a.replace("{","")
        if vanfor == -1:
            vanfor=a.find("for")
        if vanif == -1:
            vanif=a.find("if")
        if (vanfor > -1) or (vanif > -1):
            a=a.replace("print","   print")
        if j != (len(allWords[i]))-1:
            allWords[i][j]=a+" "
        print allWords[i][j],

Could someone help me, please? Thanks in advance!


Solution

  • If you change the very end of your program:

        # print allWords[i][j],
        print a,
    

    the output becomes:

    import sys  
    
    n = int(sys.argv[1]) 
    print "Beginning of the program!"
    
    for i in range(1,n) :
       print "The number:"
       print i
    
    if n < 5 :
       print n 
       print "less than 5"  
    

    Looks pretty close to what you want. To output to an open file object g, instead of stdout, just another tiny change at the program's very end...:

        # print allWords[i][j],
        print>>g, a,