【发布时间】:2018-08-28 17:02:56
【问题描述】:
我正在阅读一个 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:]
它说:如果索引
输出应如下所示
<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:
【问题讨论】:
-
你为什么要这样做?您是否要永久更改文件中的这些行?你要在网页中显示这个吗?您是否只对模块 docstrings 或文件中的任何文档字符串感兴趣?
-
我希望 Python 代码在 HTML 编辑器中使用,以便具有特殊颜色的 Python 关键字(例如:if、else、True、False、def 等颜色为黄色)得到显示这些关键字所需的 HTML。
-
不,我不想永久更改这些行,我所做的是创建一个文件,将所有带有 HTML 代码的 python 代码添加到其中,所以我只是在阅读 python 文件并调整它并将调整后的代码发送到一个新文件。
标签: python html file while-loop line