#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()
執行結果:python
E:\workspace-python\test>py -3 b.py 文件的統計信息以下: 文件中包含的數字數量:19 文件中包含的非空白字符數量:42 文件中包含的空白字符數量:9 文件中包含的行數:7