gpt4 book ai didi

python - 如何计算 Python 中不包括注释和文档字符串的代码行数?

转载 作者:IT老高 更新时间:2023-10-28 21:03:16 25 4
gpt4 key购买 nike

我想尽可能准确地计算多文件 Python 项目中的代码行数,但总数中不包括注释、文档字符串或空行。

我第一次尝试使用 cloc,它作为 Debian 软件包提供。但是 cloc 将大多数文档字符串视为代码 - 即使它们是注释。 (更新: 不再 - 最新版本的 cloc 现在将 Python 文档字符串视为注释。)

我注意到下面的一些评论说文档字符串应该包含在总数中,因为它们可能被代码用来影响运行时的行为,因此算作程序代码/数据/配置的一部分。一个突出的例子是“ply”,它要求你编写带有文档字符串的函数,据我记忆,这些函数包含对程序操作至关重要的语法和正则表达式。然而,在我看来,这似乎是一个非常罕见的异常(exception)。大多数时候,文档字符串的行为就像注释一样。具体来说,我知道一个事实对于我想要测量的所有代码都是正确的。所以我想从我的行数中排除它们。

最佳答案

Tahar不计算文档字符串。这是它的 count_loc 函数:

def count_loc(lines):
nb_lines = 0
docstring = False
for line in lines:
line = line.strip()

if line == "" \
or line.startswith("#") \
or docstring and not (line.startswith('"""') or line.startswith("'''"))\
or (line.startswith("'''") and line.endswith("'''") and len(line) >3) \
or (line.startswith('"""') and line.endswith('"""') and len(line) >3) :
continue

# this is either a starting or ending docstring
elif line.startswith('"""') or line.startswith("'''"):
docstring = not docstring
continue

else:
nb_lines += 1

return nb_lines

关于python - 如何计算 Python 中不包括注释和文档字符串的代码行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9076672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com