[python每日一练]--0007:代码统计

题目链接:https://github.com/Show-Me-the-Code/show-me-the-code
我的github链接:https://github.com/wjsaya/python_spider_learn/tree/master/python_daily
个人博客地址:https://wjsaya.github.io
第 0007 题:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。

思路:

  1. 列出目录下所有py文件;
  2. 依次逐行读取py文件;
  3. 循环加判断,根据结果来更改数组的值,数组里就是统计结果。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/env python3
#coding: utf-8
#Auther: wjsaya
#**第 0007 题:**有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。
import os
import re
def file_list(dir):
os.chdir(dir)
F_list = [ F for F in os.listdir("./") if os.path.splitext(F)[1]==".py"]
for name in F_list:
result = word_count(name)
print (name+"中,注释为"+str(result[0])+"行,空行为"+str(result[1])+"行,有效代码行数为"+str(result[2]))
def word_count(name):
count = [0, 0, 0]
#第一个为注释,第二个为空格,第三个为代码
file = open(name, 'r', encoding="utf-8").readlines()
for line in file:
if re.match(r'[ ]*#', line):
count[0] += 1
elif re.match(r'$', line):
count[1] += 1
else:
count[2] += 1
return count
if __name__ == "__main__":
#dir = input("输入代码目录:")
dir = "code"
file_list(dir)

效果图:

0007


ps:懒癌发作的日常。。。离上一篇已经过去了10天233,慢慢来,不着急。。。
另外,我的个人博客是托管在最大的同性交友网站,不是,是最大的代码托管平台github上的,所以访问可能会有点慢ԅ(¯㉨¯ԅ)

0%