我正在阅读一个python文件,我想找到一条有以下内容的行:" " "评论。在找到它之后,我想从该python文件中获取以下几行来获取一些HTML代码,直到结束引号" " "评论。
Python文件示例:
"""
Some comment in this area
Another line with comment
Some more
More
"""
def main():
var = something
file = somefile
for i in x:
我尝试过的代码但是并没有真正起作用:
def main():
file = open("pythonfile.py","r")
infile = file.readlines()
flag = False
for line in infile:
while len(line) > 0:
if flag:
index = line.find("\'\'\'")
if index < 0:
print("<span style=\"color: green;\">",line[:],"</span>",end="")
flag = True
line = ""
else:
print("<span style=\"color: green;\">",line[0:index+3],"</span>",end="")
flag = False
line = line[index+3:]
其中所说:if index&lt; 0:我希望在程序找到引号后,以下所有行都会得到绿色的跨度颜色,直到找到结束引号。
输出应如下所示
<span style=\"color: green;\">"""</span>
<span style=\"color: green;\">Some comment in this area </span>
<span style=\"color: green;\">Another line with comment</span>
<span style=\"color: green;\">Some more</span>
<span style=\"color: green;\">More</span>
<span style=\"color: green;\">"""</span>
def main():
var = something
file = somefile
for i in x:
答案 0 :(得分:0)
file = open("pythonfile.py" ,"r")
infile = file.readlines()
flag = False
# headop = True
for line in infile:
line2=line
if line[-1]=='\n':
line2=line[:-1]
index=line2.find("\"\"\"")
if index>=0:
index2 = line2[index+3:].find("\"\"\"")
if index2>=0:
index2+=(index+3)
else:
index2=-1
if index<0:
if flag:
print("<span style=\"color: green;\">" ,line2 ,"</span>", sep="")
else:
print(line2)
else:
if flag:
print("<span style=\"color: green;\">" ,line2[0:index+3] ,"</span>", end="", sep="")
if index2<0:
print(line2[index+3:])
flag=False
else:
print(line2[index+3:index2], end="")
print("<span style=\"color: green;\">" ,line2[index2:] ,"</span>", sep="")
flag=True
else:
print(line2[0:index], end="")
if index2<0:
print("<span style=\"color: green;\">" ,line2[index:] ,"</span>", sep="")
flag=True
else:
print("<span style=\"color: green;\">" ,line2[index:index2+3] ,"</span>", end="", sep="")
print(line2[index2+3:])
flag=False
输出
<span style="color: green;">"""</span>
<span style="color: green;"></span>
<span style="color: green;">Some comment in this area</span>
<span style="color: green;"></span>
<span style="color: green;">Another line with comment</span>
<span style="color: green;"></span>
<span style="color: green;">Some more</span>
<span style="color: green;">More</span>
<span style="color: green;"></span>
<span style="color: green;">"""</span>
def main():
<span style="color: green;">""" this is a test</span>
<span style="color: green;"> in code block """</span>
var = 'something'
var2 = <span style="color: green;">"""different"""</span>
var3 = <span style="color: green;">"""diff1"""</span>
file = 'somefile'
for i in range(10):
print("i=",i)
str = <span style="color: green;">""" this is a test</span>
<span style="color: green;"> and test and test. """</span>
print("str=",str)
<span style="color: green;">""" call main() """</span>
main()