#-*-coding:utf-8-*-#python#Xiaodeng#counts the number of occurrences of a character ' a ' in a file#http://www.cnblogs.com/hongten/p/hongten_python_count.htmlImportOsnumber=0defGetNumber (filepath,c):'c---->the Word numbers' #counts the number of occurrences of a character ' a ' in a file ifos.path.exists (filePath):GlobalNumber with open (FilePath,'R') as FP: forLineinchFp:countnumber=Line.count (c) number=number+CountNumberElse: Print 'The path:[{}] is not exist!'. Format (filePath)#number of numbers returned #return numberif __name__=='__main__': File_path='OUT.txt' PrintGetNumber (File_path,'Xiaodeng') #Number is a global variable and can be output directly Print Number#make some modifications to the above case:Print '**'*20defGetNumber (filepath,c):ImportOSifos.path.exists (FilePath): number=0 with open (FilePath,'R') as FP: forLineinchFp:countnumber=Line.count (c) number=number+CountNumberreturn NumberElse: Print 'The path:[{}] is not exist!'. Format (filePath)if __name__=='__main__': File_path='OUT.txt' PrintGetNumber (File_path,'Xiaodeng')
Counts the number of occurrences of a character ' a ' in a file