社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

Maddu Swaroop

Maddu Swaroop 最近创建的主题
Maddu Swaroop 最近回复了
3 年前
回复了 Maddu Swaroop 创建的主题 » 如何在python中计算空行数

什么时候 len(line.strip()) == 0 你必须增加 empty_line 而且

你可以用这个

 import sys
    def read():
        file_name = input("Name of the file to be read: ")
        try:
            file = open(file_name, 'r')
            lst = []
            line_num = 0
            accept_line = 0
            reject_line = 0
            empty_line = 0
            for line in file:
                line = line.strip() 
                if (len(line.strip()) == 0):
                    line_num += 1
                    empty_line += 1
                if (line == "\n"):
                    line_num += 1
                if (len(line) != 0):
                    line_num += 1
                if (line.isalpha()):
                    accept_line += 1
                    lst.append(line)
                else:
                    reject_line += 1
            print("Read {} lines".format(line_num))
            print("Rejected {} lines".format(reject_line))
        except FileNotFoundError:
            print("open", file_name, "failure.")
            sys.exit(0)
        file.close()
        return lst, accept_line