我有一个文件,其中包含:
<html>
<h1>Hello There</h1>
<p>
This is an example of a pml file
</p>
<pml>
def f():
return "<h2>First PML block</h2>"
pml = f()
</pml>
<p>Here is another paragraph</p>
<pml>
def g():
return "<h2>Second PML block</h2>"
pml = g()
</pml>
<p>This is the last paragraph.</p>
<pml>
def h():
return "<h2>Third PML block</h2>"
pml = h()
</pml>
</html>
我正在编写一个 python 脚本,它将生成一个输出文件,该文件将 pml 块替换为块中代码的结果。我希望输出文件看起来像:
<html>
<h1>Hello There</h1>
<p>
This is an example of a pml file
</p>
<h2>First PML block</h2>
<p>Here is another paragraph</p>
<h2>Second PML block</h2>
<p>This is the last paragraph.</p>
<h2>Third PML block</h2>
</html>
这是我的脚本:
import sys
#define main
def main(argv):
#make sure usage is proper
if len(sys.argv) != 3:
print 'Usage: pmlparser.py <input_file> <output_file>'
else:
#get the filenames
inputfilename = sys.argv[1]
outputfilename = sys.argv[2]
#open the files
with open(inputfilename,"r") as inputfile, open(outputfilename,"w") as outputfile:
for line in inputfile:
if not "<pml>" in line:
outputfile.write(line)
else:
pmlfile = open("pmlcode.py","a")
for line in inputfile:
if not "</pml>" in line:
pmlfile.write(line[1:])
else:
#I think the problem is somewhere in here
pmlfile.close()
import pmlcode
outputfile.write(pmlcode.pml + "\n")
break
if __name__ == "__main__":
main(sys.argv[1:])
不幸的是,我得到以下结果:
<html>
<h1>Hello There</h1>
<p>
This is an example of a pml file
</p>
<h2>First PML block</h2>
<p>Here is another paragraph</p>
<h2>First PML block</h2>
<p>This is the last paragraph.</p>
<h2>First PML block</h2>
</html>
我正在迭代导入 pmlcode.py,并尝试将 pml 的新值写入输出文件。但是,此脚本不断将 pml 的原始值写入输出文件。
我尝试了以下测试:
一个.py:
def f():
return 1
var = f()
def g():
return 2
var = g()
b.py:
import a
print a.var
$> python b.py
2
我昨天刚开始学习 Python,所以如果我的问题听起来很愚蠢或者我误解了什么,我深表歉意。我很感激任何帮助!