生成Python文件

发布于 2024-09-03 19:20:21 字数 1769 浏览 0 评论 0原文

我对 python 有疑问(抱歉之前我的个人感受..:P)。

我有一个 txt 文件,它包含自定义语言,我必须将其翻译为可用的 python 代码。

输入:

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"}  

想要的输出看起来完全像这样:

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"    

输入文件的名称是从参数中读取的。输出文件是out.py。如果参数错误,则会给出错误消息。这 ;;意味着新的一行。

当我尝试这样做时,我创建了一个数组,将所有行读入其中,并用“”分隔。然后我想把它从我不需要的标记中去掉。我做了两个循环,一个用于台词,一个用于单词。然后我就开始更换东西。一切都很顺利,直到到达 } 标记。它找到了它,但无法替换或剥离它。我不知道该怎么办。

我的代码(很乱,目前没有写入文件):

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],

有人可以帮助我吗? 提前致谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

始终不够 2024-09-10 19:20:21

如果您更改程序的最后部分:

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

输出将变为:

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"  

看起来非常接近您想要的。要输出到打开的文件对象 g,而不是 stdout,只是程序最后的另一个微小更改......:

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

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,
临走之时 2024-09-10 19:20:21

快速解决这个问题(如果您将其用于家庭作业,请确保您了解发生了什么;遵循良好的 Python 语言教程可能会有所帮助):

import sys
filename = sys.argv[1]

replace_dict = { ";;": "\n", "LOOP": "for", "BRANCH": "if", "{": ":{" }
indent_dict = { "{": 1, "}": -1, "\n": 0 }

lines = open(filename).readlines()
indent, output, pop_next_newline = 0, [], False

for line in lines:
    for key, value in replace_dict.iteritems():
        line = line.replace(key, value)
    for char in line:
        if char in indent_dict:
            indent += indent_dict[char]
            if pop_next_newline and char == "\n":
                pop_next_newline = False
            else:
                output.append("\n%s" % ("    " * indent))
            if char == "}": 
                pop_next_newline = True
        else:
            output.append(char)

print ''.join(output)  

A quick go at the problem (if you use it for homework make sure you understand what's going on; following a good Python language tutorial may help):

import sys
filename = sys.argv[1]

replace_dict = { ";;": "\n", "LOOP": "for", "BRANCH": "if", "{": ":{" }
indent_dict = { "{": 1, "}": -1, "\n": 0 }

lines = open(filename).readlines()
indent, output, pop_next_newline = 0, [], False

for line in lines:
    for key, value in replace_dict.iteritems():
        line = line.replace(key, value)
    for char in line:
        if char in indent_dict:
            indent += indent_dict[char]
            if pop_next_newline and char == "\n":
                pop_next_newline = False
            else:
                output.append("\n%s" % ("    " * indent))
            if char == "}": 
                pop_next_newline = True
        else:
            output.append(char)

print ''.join(output)  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文