鱼C论坛

 找回密码
 立即注册
查看: 964|回复: 2

课后习题疑问

[复制链接]
发表于 2018-5-6 13:09:42 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 新手·ing 于 2018-5-6 13:41 编辑

问题:
1、麻烦大神帮忙,这代码的整体结构组成(实现需求=1+2+3)
2、一些关键代码给个注释
3、下面这段代码是怎么统计行数的?   
for i in source_list:
        lines = source_list[i] #统计行数

4、写一个程序统计当前代码量的总和,并显示离十万行代码量还有多远?
要求一:递归搜索各个文件夹
要求二:显示各个类型的源文件代码数量
要求三:显示总行数与百分比

66283A54E7444B06A656E19E206DD2F8.jpg
8DE51C14E6E641C4A0A041DDF5D3560D.jpg

代码:
  1. import easygui as g
  2. import os

  3. def show_result(start_dir): #新建结果显示函数
  4.     lines = 0
  5.     total = 0
  6.     text = ""

  7.     for i in source_list:
  8.         lines = source_list[i] #统计行数
  9.         total += lines
  10.         text += "【%s】源文件 %d 个,源代码 %d 行\n" % (i, file_list[i], lines)
  11.     title = '统计结果'
  12.     msg = '您目前共累积编写了 %d 行代码,完成进度:%.2f %%\n离 10 万行代码还差 %d 行,请继续努力!' % (total, total/1000, 100000-total)
  13.     g.textbox(msg, title, text)

  14. def calc_code(file_name):
  15.     lines = 0
  16.     with open(file_name) as f:
  17.         print('正在分析文件:%s ...' % file_name)
  18.         try:
  19.             for each_line in f:
  20.                 lines += 1
  21.         except UnicodeDecodeError:
  22.             pass # 不可避免会遇到格式不兼容的文件,这里忽略掉......
  23.     return lines

  24. def search_file(start_dir) :
  25.     os.chdir(start_dir)
  26.    
  27.     for each_file in os.listdir(os.curdir) :
  28.         ext = os.path.splitext(each_file)[1]
  29.         if ext in target :
  30.             lines = calc_code(each_file) # 统计行数
  31.             # 还记得异常的用法吗?如果字典中不存,抛出 KeyError,则添加字典键
  32.             # 统计文件数
  33.             try:
  34.                 file_list[ext] += 1
  35.             except KeyError:
  36.                 file_list[ext] = 1
  37.             # 统计源代码行数
  38.             try:
  39.                 source_list[ext] += lines
  40.             except KeyError:
  41.                 source_list[ext] = lines
  42.             
  43.         if os.path.isdir(each_file) :
  44.             search_file(each_file) # 递归调用
  45.             os.chdir(os.pardir) # 递归调用后切记返回上一层目录
  46.             
  47. target = ['.c', '.cpp', '.py', '.cc', '.java', '.pas', '.asm']
  48. file_list = {}
  49. source_list = {}

  50. g.msgbox("请打开您存放所有代码的文件夹......", "统计代码量")
  51. path = g.diropenbox("请选择您的代码库:")

  52. search_file(path)
  53. show_result(path)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-5-6 14:00:18 | 显示全部楼层
for each_line in f:
                lines += 1
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2018-5-8 14:41:57 | 显示全部楼层
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-12-30 00:42

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表