在python中读取时忽略文本文件中的多行注释

2024-09-30 22:18:59 发布

您现在位置: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())

Tags: or方法代码目录脚本returnifdef
1条回答
网友
1楼 · 发布于 2024-09-30 22:18:59

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

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

相关问题 更多 >