#有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释
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')