首页 > 解决方案 > 在 python 中读取时忽略文本文件中的多行注释

问题描述

我正在尝试使用 python 脚本计算目录中多个文本文件中有多少行代码。我想出了以下方法,但它仅在注释在一行而不是多行时才有效。有没有办法做到这一点?

def remove_comments(line):
    if line.startswith('/*') or line.endsswith('*/'):
        return 0
    else:
        return 1

count = sum(remove_comments(line) for line in f if line.strip())

标签: pythoncountreadfile

解决方案


一个肮脏的黑客可能是使用全局变量:

with open("test", 'r') as f_in:
    f = f_in.readlines()

is_in_comment = False

def remove_comments(line):
    global is_in_comment
    line = line.strip()

    if line.startswith('/*'):
        is_in_comment = True
        return 0
    elif line.endswith('*/'):
        is_in_comment = False
        return 0

    return 0 if is_in_comment else 1

count = sum(remove_comments(line) for line in f if line.strip())

这假设你不能*/没有以前的/*但是。此代码为以下test文件返回 3:

That is one line
Another
/* Comment
Other comment
End comment */
Final line, not a comment

推荐阅读