使用python计数python文件中的注释行和注释块数

时间:2019-06-02 17:45:34

标签: python python-3.x comments

当前,我正在尝试创建一个python脚本,用于计算python文件中的注释行和注释块的数量。

我尝试使用正则表达式,但没有成功。现在,我只是使用常规的for和if来弄清楚。现在,我正在尝试找出一个块中有多少条注释行,并将其与文件中注释行的总数相减,以获得单行注释的数量。

it = iter(lines) # lines is a list that contains all the lines that are in the file
for each_ in lines:
    each_ = each_.strip()
    if each_.startswith('#'): # If a line starts with a '#' move to the next line
        next(it)
        print(each_)
        if each_.startswith('#') is True: # If the next line starts with a '#' increment d 
            d += 1 # d is the value for: Comment lines in a block

示例python文件:

# a
# b
# c
Line 1
Line 2
Line 3
    # d
# e
f

预期输出为:

注释块= 1(以相同的方向出现在下一行上的#数倍[a,b,c是1个注释块的一部分,而d,e不是注释块])

注释行= 3

单行注释= 2

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

single_lines = []
blocks = []
block = []
block_position = 0
for line in lines.splitlines():
    try:
        position = line.index('#')  # Find the index of the first #
    except ValueError:
        position = -1
    line = line.lstrip()
    if line.startswith('#'):
        # If current block position match the new one
        if block_position == position:
            # Part of the same block, adding to the list
            block.append(line)
        else:
            # adding the previous block
            if len(block) > 0:
                if len(block) == 1:
                    single_lines.append(block)
                else:
                    blocks.append(block)
            # Starting a new block
            block = [line]
            block_position = position
    else:
        # Means that there is no # in the line
        if len(block) > 0:
            # If block was not empty we are closing it
            if len(block) == 1:
                single_lines.append(block)
            else:
                blocks.append(block)
            block_position = 0
            block = []
else:
    # Validation if at the end of the loop we still have a block that was not closed
    if len(block) > 0:
        if len(block) == 1:
            single_lines.append(block)
        else:
            blocks.append(block)

打印格式解决方案:

print('Total of Blocks: {}'.format(len(blocks)))
print('Total of single lines: {}'.format(len(single_lines)))
for idx, block in enumerate(blocks):
    print('Block {} - contains {} lines :\n{}'.format(idx, len(block), '\n'.join(block)))

输入1

# a
# b
# c
Line 1
Line 2
Line 3
    # d
# e
f

输出1

[['# a', '# b', '# c'], ['# d'], ['# e']]

输入2:

# a
# b
# c
Line 1
Line 2
Line 3
    # d
    # e
# f
f
# g
# h

输出2:

[['# a', '# b', '# c'], ['# d', '# e'], ['# f'], ['# g', '# h']]

输出2:采用以下格式:

Total of Blocks: 3
Total of single lines: 1
Block 0 - contains 3 lines :
# a
# b
# c
Block 1 - contains 2 lines :
# d
# e
Block 2 - contains 2 lines :
# g
# h