Python 练习 06 有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释

#有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释
import os
import re

os.chdir('文件路径')

fh=open('文件名', 'r', encoding='utf-8')
read_fh=fh.readlines()
fh.close()
number_code=0
number_empty=0
number_note=0
pattern='.*#' #正则匹配模式

for x in read_fh:
    if '#' in x : #计算注释数目
        if re.findall(pattern,x)[0][:-1].isspace() or re.findall(pattern,x)[0][:-1]=='':
            number_note+=1
        else:
            number_code+=1

    elif x.isspace():
        number_empty+=1
    else:
        number_code+=1
print ('code number is %d'%(number_code+number_empty+number_note))
print ('empty number is %d'%number_empty)
print ('note number is %d'%number_note)
2.
import os.pat
def mainKeywords(dirPath):
    blank, comments, codelines, totalines, count, temp = 0, 0, 0, 0, 0, 0
    f_list = os.listdir(dirPath)
    for i in f_list:
        if os.path.splitext(i)[1] == '.py':
            print(i)
            with open(i, 'r', encoding='utf-8') as fp:
                while True:
                    line = fp.readline()
                    totalines += 1
                    if not line:
                        break
                    elif line.strip().startswith('#'):
                        comments += 1
                    elif line.strip().startswith("'''") or line.strip().startswith('"""'):
                        comments += 1
                        if line.count('"""') == 1 or line.count("'''") == 1:
                            while True:
                                line = fp.readline()
                                totalines += 1
                                comments += 1
                                if ("'''" in line) or ('"""' in line):
                                    break
                    elif line.strip():
                        codelines += 1
                    else:
                        blank += 1
                print('the nuber of totalines is : ' + str(totalines-1))
                print('the nuber of comments is : ' + str(comments))
                print('the nuber of codelines is : ' + str(codelines))
                print('the nuber of blanklines is : ' + str(blank))
                blank, comments, codelines, totalines = 0, 0, 0, 0

mainKeywords('E:/Users/summer/PycharmProjects/untitled')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值