我和团队的其他成员需要处理一堆 MATLAB 脚本/函数文件。我们几乎不知道大多数文件的用途,也几乎不知道哪些文件属于在一起,哪些文件是独立的。我们确实知道总共有 36,000 行。我想知道其中有多少行是注释。
很简单,对吧?只需计算其中有多少以评论起始字符 % 开头即可。
嗯,不。我不想计算已被注释为“注释”的代码块,因为它们实际上并没有告诉我任何信息。而且我不想计算用于使一个评论行成为“标题”的“空”行
% %%%%%%%%
% headline
% %%%%%%%%
就像这样。
那么我怎样才能合理估计我有多少行实际信息性评论?有没有一种简单的方法可以区分自然语言(可能包含代码片段)和纯代码?
是的,我知道代码在实用的情况下应该是不言自明的,但我们继承的代码显然不是。是的,我知道我们应该重构这个烂摊子。计算出我们有多少评论的目的是为了突出我们在这里的技术债务,以便我们可以为这次重构分配资源。
最佳答案
我们可以使用半文档化的 mtree
实用程序来实现此目的。
让我们以包含 mtree
类本身定义的 .m
文件为例。
dbtype mtree
产生(这只是开始):
1 classdef mtree
2 %MTREE Create and manipulate M parse trees
3 % This is an experimental program whose behavior and interface is likely
4 % to change in the future.
5
6 % Copyright 2006-2016 The MathWorks, Inc.
7
8 properties (SetAccess='protected', GetAccess='protected', Hidden)
9 T % parse tree array
现在,如果我们调用 mtree
实用程序并将结果显示为文本,
tree = mtree('mtree.m','-file');
tree.dumptree()
这是我们得到的结果(同样,这只是开始):
1 *: CLASSDEF: 1/01 3 *Cexpr: ID: 1/10 (mtree) 4 *Body: PROPERTIES: 8/05 5 *Attr: ATTRIBUTES: 8/16 6 *Arg: ATTR: 8/26 7 *Left: ID: 8/17 (SetAccess) 8 *Right: CHARVECTOR: 8/27 ('protected') 9 >Next: ATTR: 8/49 10 *Left: ID: 8/40 (GetAccess) 11 *Right: CHARVECTOR: 8/50 ('protected') 12 >Next: ATTR: 8/63 13 *Left: ID: 8/63 (Hidden) 14 *Body: EQUALS: 9/09
As you can see from the above, comment and empty lines (2-7) do not appear on the left side of the "fractions" in the output.. So if we find a way to get the "numerators", we'll get the numbers of the lines that contain actual code.
We're in luck, since there exists a method that gives us these numerators - lineno
! So if we call it and apply unique
to the output, we'll get exactly one copy of each line:
uLines = unique(tree.lineno);
nCodeLines = numel(uLines);
在 R2018b 中,nCodeLines
的值为 269
。如果您愿意假设文件中的最后一行始终是一行代码(而不是注释或空白),则只需从 的最后一个元素中减去
获取注释行数(在本例中为 nCodeLines
uLines121
)。否则,使用其他一些技术来计算总行数 ( example )。
剩下的就是将其编写为函数并将 .m
文件的文件夹提供给它:)
关于matlab - 如何计算实际评论的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53191087/