加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

是否有工具从python源提取所有注释,保留源代码行/ col信息?

发布时间:2020-12-20 11:44:27 所属栏目:Python 来源:网络整理
导读:是否有任何 python库或工具允许我从 python源代码块中提取所有注释,最好保留有关原始行和列的信息?例如 PYCODE = """# Comment 1x = "#Notacomment"##### Comment 2 #####""".strip()print(get_comments(PYCODE)) [(“#Comment 1”,0),(“##### Comment 2 #
是否有任何 python库或工具允许我从 python源代码块中提取所有注释,最好保留有关原始行和列的信息?例如

PYCODE = """
# Comment 1
x = "#Notacomment"
##### Comment 2 #####
""".strip()
print(get_comments(PYCODE))

[(“#Comment 1”,0),(“##### Comment 2 #####”,2,0)]

解决方法

您可以使用 tokenize module扫描注释.这是一个基本上输出你想要的片段:

import tokenize,io

code_string = """
# Comment 1
x = "#Notacomment"
##### Comment 2 #####
"""

buf = io.StringIO(code_string)

for line in tokenize.generate_tokens(buf.readline):
    if line.type == tokenize.COMMENT:
        print(line)

这输出:

TokenInfo(type=54 (COMMENT),string='# Comment 1',start=(2,end=(2,11),line='# Comment 1n')
TokenInfo(type=54 (COMMENT),string='##### Comment 2 #####',start=(4,end=(4,21),line='##### Comment 2 #####n')

请参阅文档以了解如何使用TokenInfo实例.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读