寫一個類,能夠統計某個檔案的純數字字元個數,統計非空白個數,空白字元個數,檔案行數,檔案所在路徑,通過繼承方式,增加一個方法,列印所有的統計資訊
阿新 • • 發佈:2018-12-01
#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