← 中文资源

简体中文版本

tokenize 找出字符串之外的注释

generate_tokens 按词法规则切分源码,COMMENT 只发给真正的注释;引号里的 # 只是文本,统计或替换注释时不会误伤字符串。

阅读英文原文

实现说明

这个文件只在 for token in tokenize.generate_tokens(io.StringIO(source).readline) 里循环。 source、greeting、total、comments 定义在模块顶层,中间不经过函数作用域。

使用要点

  • tokenize 必须先装好——示例直接导入它们。

常见问题

它需要从包仓库拿什么?

这些是真实的依赖:tokenize。缺了就加载不起来。

核心语句

for token in tokenize.generate_tokens(io.StringIO(source).readline):
    if token.type == tokenize.COMMENT:
        comments.append(token.string)
for comment in comments:
    print(" ", comment)

代码示例

import io
import tokenize

source = '''route = "/reports/<id>"  # endpoint for the export
greeting = "hi # there"  # the # inside quotes stays text
# TODO: paginate the export
total = len(route)  # trailing note
'''

comments = []
for token in tokenize.generate_tokens(io.StringIO(source).readline):
    if token.type == tokenize.COMMENT:
        comments.append(token.string)

print(f"{len(comments)} comments outside strings")
for comment in comments:
    print(" ", comment)