• 007使用python统计代码行数,空行以及注释


    # 自己写过的程序,统计一下你写过多少行代码。包括空行和注释,但是要分别列出来

    1.打开文件方法

    1.1 以读文件的模式打开一个文件对象,使用Python内置的open()函数,传入文件名和标示符

    f = open('/Users/michael/test.txt', 'r')

    1.2 Python引入了with语句来自动帮我们调用close()方法

    with open('/path/to/file', 'r') as f:
        print(f.read())

    1.3 调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list

    for line in f.readlines():
        print(line.strip()) # 把末尾的'\n'删掉

    2.python计算文件行数的三种方法

    def linecount_1():
        return len(open('data.sql').readlines())#最直接的方法
    
    def linecount_2():
        count = -1 #让空文件的行号显示0
        for count,line in enumerate(open('data.sql')): pass 
        #enumerate格式化成了元组,count就是行号,因为从0开始要+1
        return count+1
    
    def linecount_3():
        count = 0
        thefile = open('data.sql','rb')
        while 1:
            buffer = thefile.read(65536)
            if not buffer:break
            count += buffer.count('\n')#通过读取换行符计算
        return count

    3.Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

    注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

    stip()方法语法:

    str.strip([chars]);

    4.startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查

    startswith()方法语法:

    str.startswith(substr, beg=0,end=len(string))

    完整代码:

    # conding:utf-8

    count = 0 sum = 0 catalog = open(r"D:\Users\sky\PycharmProjects\untitled2\dict.py") t = len(open(r"D:\Users\sky\PycharmProjects\untitled2\dict.py").readlines())  #统计行数 for line in catalog.readlines(): line = line.strip() #去掉每行头尾空白 print(line) if line == "": count += 1 if line.startswith("#"): #startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False sum += 1 print("统计的文件行数为:%d行" %t) print("统计文件的空行数为:%s" %count) print("统计的注释行数为:%s" %sum)
  • 相关阅读:
    Uncaught TypeError: Cannot set property 'onclick' of null
    Linuxe lftp命令(七)
    linux yum 命令(六)
    Linux vi/vim(五)
    Linux 文件与目录管理(四)
    Linux 文件基本属性(三)
    Linux 系统目录结构(二)
    Linux 系统启动过程(一)
    Java基础语法知识(笔记)——(三)泛型,String与正则
    Java基础语法知识(笔记)——(二)类与对象,接口,多态,继承,异常
  • 原文地址:https://www.cnblogs.com/kkkhycz/p/11639235.html
Copyright © 2020-2023  润新知