|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 木一 于 2017-8-12 15:09 编辑
能够正常运行,没有报错,但是计算结果不对,请问哪里有问题?计算结果显示代码只有72行,明显不对,但是源文件数是对的。- import easygui as g
- import os
- def show_result(start_dir):
- lines = 0
- total = 0
- text = ''
- for i in source_list:
- lines = source_list[i]
- total += lines
- text += '%s源文件%d个,源代码%d行\n'%(i,file_list[i],lines)
- title = '统计结果'
- msg = '您目前累计共编写了%d行代码,离十万行还差%d行,请继续努力!'%(total,100000-total)
- g.textbox(msg,title,text)
- def calc_code(file_name):
- lines = 0
- with open(file_name) as f:
- print('正在分析文件:%s...'%file_name)
- try:
- for each_line in f:
- lines += 1
- except UnicodeDecodeError:
- pass
- return lines
- def search_file(start_dir):
- os.chdir(start_dir)
- for each_file in os.listdir(os.curdir):
- ext = os.path.splitext(each_file)[1]
- if ext in target:
- lines = calc_code(each_file)
- try:
- file_list[ext] += 1
- except KeyError:
- file_list[ext] = 1
- try:
- source_list[ext] += lines
- except KeyError:
- source_list[ext] = lines
- if os.path.isdir(each_file):
- search_file(each_file)
- os.chdir(os.pardir)
- target = ['.c','.cpp','.py']
- file_list = {}
- source_list = {}
- g.msgbox('请打开您存放所有代码的文件夹......','统计代码量')
- path = g.diropenbox('请选择您的代码库:')
- search_file(path)
- show_result(path)
-
复制代码
try:
for each_line in f:
lines += 1
except UnicodeDecodeError:
pass
这个位置忽略了不能读取的文件
参考:
- https://pypi.python.org/pypi/chardet
- import chardet
- #以rb读取文件返回文件的编码(用到了chardet类)
- with open(file_name, 'rb') as f:
- raw = f.read()
- result = chardet.detect(raw)
- encoding = result['encoding']
- lines = 0
- with open(file_name,encoding=encoding) as f:
- print('正在分析文件:%s ...' % file_name)
- try:
- for each_line in f:
- lines += 1
- except Exception as reason:
- print(str(reason)) # 读取出错显示错误信息......
- print('%s -> %s' % (file_name,lines))
- return lines
复制代码
|
-
|