如何计算python中全行注释的行数?

时间:2017-01-31 23:08:54

标签: python python-3.x

我正在尝试创建一个接受文件作为输入的函数,并打印全行注释的行数(即该行以#follow with some comments开头)。

例如,包含以下行的文件应该打印结果2:

abc
#some random comment
cde
fgh
#another random comment

到目前为止,我尝试了但却没有拿起哈希符号:

infile = open("code.py", "r")
line = infile.readline()

def countHashedLines(filename) :

     while line != "" :
           hashes = '#'
           value = line
           print(value) #here you will get all
           #if(value == hashes):  tried this but just wasn't working
           #      print("hi")
           for line in value:
           line = line.split('#', 1)[1]
           line = line.rstrip()
           print(value)
           line = infile.readline()
   return()

提前致谢, 杰马

3 个答案:

答案 0 :(得分:1)

为了便于使用(主观),我重新措辞了一些陈述,但这会给你想要的输出。

def countHashedLines(lines):
    tally = 0
    for line in lines:
        if line.startswith('#'): tally += 1
    return tally

infile = open('code.py', 'r')
all_lines = infile.readlines()

num_hash_nums = countHashedLines(all_lines) # <- 2

infile.close()

...或者如果你想要一个紧凑而干净的功能......

def countHashedLines(lines):
    return len([line for line in lines if line.startswith('#')])

答案 1 :(得分:0)

我会通过标准输入传递文件

import sys

count = 0 

for line in sys.stdin: """ Note: you could also open the file and iterate through it"""
    if line[0] == '#': """ Every time a line begins with # """
        count += 1 """ Increment """


print(count)

答案 2 :(得分:0)

这是另一种使用正则表达式的解决方案,它将检测前面有空格的注释。

import re

def countFullLineComments(infile) :
    count = 0
    p = re.compile(r"^\s*#.*$")
    for line in infile.readlines():
        m = p.match(line)
        if m:
            count += 1
            print(m.group(0))
    return count

infile = open("code.py", "r")
print(countFullLineComments(infile))