社区所有版块导航
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
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中计算空行数

Arthur • 3 年前 • 1287 次点击  

我正在读一个包含空行和单词的文件,例如“CAR”和“V3HICL3”。我只想把合法的单词写入另一个文件。为此,我想删除空行和有错误的单词(此处包含数字)。我还想数一数有多少行被阅读、删除和接受。我在捕捉空行时遇到问题。在我的列表中,我有:car,v3hicl3,“空”。我数不清空行。尝试了isspace和line==“\n”。似乎不管用。我该如何计算文档的最后一行空行?

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
            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", line_num, "lines")
    print("Rejected", reject_lines, "lines")
    except FileNotFoundError:
        print("open", file_name, "failure.")
        sys.exit(0)
    file.close()
    return lst, accept_line

感谢您的任何意见。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130315
 
1287 次点击  
文章 [ 2 ]  |  最新文章 3 年前