您的位置:首页 > 编程语言 > Python开发

python练手项目0007

2017-01-05 13:51 363 查看
本项目采用的是https://github.com/Yixiaohan/show-me-the-code中所提供的练习项目,所有代码均为原创,转载请注明,谢谢。

问题描述:有个目录,里面是你自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来。

代码如下:

# -*- coding: utf-8 -*-

"""

Created on Thu Jan 05 12:35:52 2017

@author: sky

"""

import os

def count_the_code(path):

    file_name = os.path.basename(path)

    note_flag = False

    line_num = 0

    empty_line_num = 0

    note_num = 0

    with open(path) as f:

        for line in f.read().split('\n'):

            line_num += 1

            if line.strip().startswith('\"\"\"') and not note_flag:

                note_flag =True

                note_num += 1

                continue

            if line.strip().startswith('\"\"\"'):

                note_flag = False

                note_num += 1

            if line.strip().startswith('#') or note_flag:

                note_num += 1

            if len(line) == 0:

                empty_line_num += 1

    print u"在%s中,共有%s行代码,其中有%s空行,有%s注释"% (file_name, line_num, empty_line_num, note_num)

    file = open('result.txt','w')

    file.write('file_name :'+ file_name)

    file.write('\n')

    file.write('line_num: ' + str(line_num))

    file.write('\n')

    file.write('empty_line:'+ str(empty_line_num))

    file.write('\n')

    file.write('note_num: ' + str(note_num))

    file.close()

if __name__ == '__main__':

        count_the_code('0007.py')

详细代码和结果,可以参考https://github.com/g8015108/exercise-for-python
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python