python乘法表代码注释_Python统计python文件中代码,注释及空白对应的行数示例【测试可用】...
本文實例講述了Python實現統計python文件中代碼,注釋及空白對應的行數。分享給大家供大家參考,具體如下:
其實代碼和空白行很好統計,難點是注釋行
python中的注釋分為以#開頭的單行注釋
或者以'''開頭以'''結尾 或以"""開頭以"""結尾的文檔注釋,如:
'''
hello world
'''
和
'''
hello world'''
思路是用is_comment記錄是否存在多行注釋,如果不存在,則判斷當前行是否以'''開頭,是則將is_comment設為True,否則進行空行、當前行注釋以及代碼行的判斷,如果is_comment已經為True即,多行注釋已經開始,則判斷當前行是否以'''結尾,是則將is_comment設為False,同時增加注釋的行數。表示多行注釋已經結束,反之繼續,此時多行注釋還未結束
# -*- coding:utf-8 -*-
#!python3
path = 'test.py'
with open(path,'r',encoding='utf-8') as f:
code_lines = 0 #代碼行數
comment_lines = 0 #注釋行數
blank_lines = 0 #空白行數 內容為'\n',strip()后為''
is_comment = False
start_comment_index = 0 #記錄以'''或"""開頭的注釋位置
for index,line in enumerate(f,start=1):
line = line.strip() #去除開頭和結尾的空白符
#判斷多行注釋是否已經開始
if not is_comment:
if line.startswith("'''") or line.startswith('"""'):
is_comment = True
start_comment_index = index
#單行注釋
elif line.startswith('#'):
comment_lines += 1
#空白行
elif line == '':
blank_lines += 1
#代碼行
else:
code_lines += 1
#多行注釋已經開始
else:
if line.endswith("'''") or line.endswith('"""'):
is_comment = False
comment_lines += index - start_comment_index + 1
else:
pass
print("注釋:%d" % comment_lines)
print("空行:%d" % blank_lines)
print("代碼:%d" % code_lines)
運行結果:
注釋:4
空行:2
代碼:26
注:這里的Python測試文件test.py如下:
# -*- coding:utf-8 -*-
#!python3
#九九乘法表
for i in range(1, 10):
for j in range(1, i+1):
print("%d*%d=%d\t" % (j, i, i*j), end="")
print()
#斐波那契數列 0,1,1,2,3,5,8,...
num=int(input("需要幾項?"))
n1=0
n2=1
count=2
if num<=0:
print("請輸入一個整數。")
elif num==1:
print("斐波那契數列:")
print(n1)
elif num==2:
print("斐波那契數列:")
print(n1,",",n2)
else:
print("斐波那契數列:")
print(n1,",",n2,end=" , ")
while count
sum=n1+n2
print(sum,end=" , ")
n1=n2
n2=sum
count+=1
print()
感興趣的朋友可以自己測試一下~
PS:這里再為大家推薦2款相關統計工具供大家參考:
希望本文所述對大家Python程序設計有所幫助。
總結
以上是生活随笔為你收集整理的python乘法表代码注释_Python统计python文件中代码,注释及空白对应的行数示例【测试可用】...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 商品领域ddd_为 Gopher 打造
- 下一篇: Graphicsmagick linux