python实现:写一个类,能够统计某个文件的纯数字字符个数,统计非空白个数,空白字符个数,文件行数,文件所在路径,通过继承方式,增加一个方法,打印所有的统计信息

#encoding=utf-8
import os.path
class FileInfo(object):
    def __init__(self,file_path,encoding_type="utf-8"):
        self.file_path=file_path
        self.encoding_type=encoding_type
        while 1:
            if not os.path.exists(self.file_path):
                self.file_path=input("请输入正确的路径:")
            else:
                break
    def get_file_content(self):
        content=""
        with open(self.file_path,encoding=self.encoding_type) as fp:
            for i in fp:
                for j in i:
                    content+=j
        return content
        
    """统计文件中的非空白字符个数"""
    def count_not_space_str(self):
        count=0
        content=self.get_file_content()
        for i in content:
            if not i.isspace():
                count+=1
        return count
        
    """统计文件中的数字字符个数"""
    def count_number_str(self):
        count=0
        content=self.get_file_content()
        for i in content:
            if i>='0' and i<='9':
                count+=1
        return count
        
    """统计文件中的空白字符个数"""
    def count_space_str(self):
        count=0
        content=self.get_file_content()
        for i in content:
            if i.isspace():
                count+=1
        return count
        
    """统计文件中的行数"""
    def count_lines(self):
        count=0
        content=self.get_file_content()
        for i in content.split("\n"):
            count+=1
        return count
        
class Advanced_FileInfo(FileInfo):
    """高级的文件信息处理类"""
    def __init__(self,file_path,encoding_type="utf-8"):
        FileInfo.__init__(self,file_path,encoding_type="utf-8")
        
    def print_file_info(self):
        print("文件的统计信息如下:")
        print("文件中包含的数字数量:%s" %self.count_number_str())
        print("文件中包含的非空白字符数量:%s" %self.count_not_space_str())
        print("文件中包含的空白字符数量:%s" %self.count_space_str())
        print("文件中包含的行数:%s" %self.count_lines())

fi = Advanced_FileInfo("e:\\b.txt")  
fi.print_file_info()

执行结果:

E:\workspace-python\test>py -3 b.py
文件的统计信息如下:
文件中包含的数字数量:19
文件中包含的非空白字符数量:42
文件中包含的空白字符数量:9
文件中包含的行数:7

 

posted @ 2018-12-01 20:44  糖葫芦有点甜  阅读(580)  评论(0编辑  收藏  举报