import os.path
import re
def mainKeywords(dirPath):
blank, comments, codelines, totalines, count, temp =0,0,0,0,0,0
f_list = os.listdir(dirPath)#获取目录下所有的文件名
for iin f_list:
if os.path.splitext(i)[1] =='.py':#分离扩张名,筛选扩张名是.py的文件
print(i)#打印扩张名是py的文件名
with open(i,'r',encoding='utf-8')as fp:#打开筛选出来的文件名
while True:
line = fp.readline()#每次读取一行,返回字符串对象
totalines +=1
if not line:
break #如果没有行,直接跳出line
elif line.strip().startswith('#'):# line.strip() 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('F:\pyxm\python源代码')