File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #!/usr/bin/env python3
2+ # -*- coding: utf-8 -*-
3+
4+ '第 0007 题:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。'
5+
6+ __author__ = 'Drake-Z'
7+
8+ import os
9+ import re
10+
11+ def count_num (a , b ):
12+ shuzi = [0 , 0 , 0 ]
13+ path = os .path .join (a , b )
14+ f = open (path , 'r' , encoding = 'UTF-8' ).readlines ()
15+ for i in f :
16+ if re .match (r'^#' , i ) == None :
17+ pass
18+ else :
19+ shuzi [1 ] += 1 #获得注释行数
20+ if f [- 1 ][- 1 :]== '\n ' : #最后一行为空行时
21+ shuzi [2 ] = f .count ('\n ' )+ 1 #获得空行行数
22+ shuzi [0 ] = len (f )+ 1 - shuzi [2 ] - shuzi [1 ] #获得代码行数
23+ else :
24+ shuzi [2 ] = f .count ('\n ' )
25+ shuzi [0 ] = len (f ) - shuzi [2 ] - shuzi [1 ]
26+ return shuzi
27+
28+ def file_analysis (c , d ):
29+ py = [x for x in os .listdir (c ) if os .path .splitext (x )[1 ]== d ] #获得文件列表
30+ print (py )
31+ the_num = [0 , 0 , 0 ]
32+ for i in py :
33+ num = count_num (c , i )
34+ the_num [0 ] += num [0 ] #累计
35+ the_num [1 ] += num [1 ]
36+ the_num [2 ] += num [2 ]
37+ print ('''统计得目录中:
38+ 代码有 %s 行
39+ 注释 %s 行
40+ 空行 %s 行''' % (the_num [0 ], the_num [1 ], the_num [2 ]))
41+
42+ if __name__ == '__main__' :
43+ file = '.'
44+ ext = '.py'
45+ file_analysis (file , ext )
Original file line number Diff line number Diff line change 1+ # -*- coding: utf-8 -*-
2+ # mydict_test.py
3+
4+ import unittest
5+ from MyMoudel .Moudel1 import Dict
6+ class TestDict (unittest .TestCase ):
7+
8+ def test_init (self ):
9+ d = Dict (a = 1 , b = 'test' )
10+ self .assertEqual (d .a , 1 )
11+ self .assertEqual (d .b , 'test' )
12+ self .assertTrue (isinstance (d , dict ))
13+
14+ def test_key (self ):
15+ d = Dict ()
16+ d ['key' ] = 'value'
17+ self .assertEqual (d .key , 'value' )
18+
19+ def test_attr (self ):
20+ d = Dict ()
21+ d .key = 'value'
22+ self .assertTrue ('key' in d )
23+ self .assertEqual (d ['key' ], 'value' )
24+
25+ def test_keyerror (self ):
26+ d = Dict ()
27+ with self .assertRaises (KeyError ):
28+ value = d ['empty' ]
29+
30+ def test_attrerror (self ):
31+ d = Dict ()
32+ with self .assertRaises (AttributeError ):
33+ value = d .empty
34+
35+ def setUp (self ):
36+ print ('setUp...' )
37+
38+ def tearDown (self ):
39+ print ('tearDown...' )
40+ if __name__ == '__main__' :
41+ unittest .main ()
You can’t perform that action at this time.
0 commit comments