用Python编写C\C++代码统计工具

举报
悦来客栈的老板 发表于 2020/12/29 00:22:32 2020/12/29
【摘要】 代码参考:https://foofish.net/how-to-count-code.html import os def parse(path): in_multi_comment = False comments,blanks,codes = 0,0,0 with open(path,'r') as fp: for scline in fp.readli...

代码参考:https://foofish.net/how-to-count-code.html




  
  1. import os
  2. def parse(path):
  3. in_multi_comment = False
  4. comments,blanks,codes = 0,0,0
  5. with open(path,'r') as fp:
  6. for scline in fp.readlines():
  7. scline = scline.strip()
  8. if scline == '' and not in_multi_comment:
  9. blanks += 1
  10. elif scline.startswith('//') or \
  11. (scline.startswith("/*") and scline.endswith("*/")) or \
  12. (in_multi_comment and not scline.endswith("*/")):
  13. comments += 1
  14. elif scline.startswith("/*") or scline.endswith("*/"):
  15. in_multi_comment = not in_multi_comment
  16. comments += 1
  17. else:
  18. codes += 1
  19. return {"comments":comments,"blanks":blanks,"codes":codes}
  20. def counter(path):
  21. if os.path.isdir(path):
  22. comments,blanks,codes = 0,0,0
  23. list_dirs = os.walk(path)
  24. for root,dirs,files in list_dirs:
  25. for f in files:
  26. file_path = os.path.join(root,f)
  27. if file_path.endswith(".c") or file_path.endswith(".h"):
  28. stats = parse(file_path)
  29. comments += stats.get("comments")
  30. blanks += stats.get("blanks")
  31. codes += stats.get("codes")
  32. return {"comments":comments,"blanks":blanks,"codes":codes}
  33. else:
  34. return parse(path)
  35. if __name__ == '__main__':
  36. print (counter("你的代码路径"))



文章来源: blog.csdn.net,作者:悦来客栈的老板,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/qq523176585/article/details/78869797

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。