python行数统计:python实现统计字符串字符出现次数

发布时间:2020-05-25编辑:脚本学堂
python如何统计字符串中指定字符的出现次数,在Python中count函数可用于行数或字符统计,这里分享了python脚本统计代码行数的例子,供大家学习参考。

一、python统计字符串中指定字符出现的次数

例如,统计字符串中空格的数量。
 

复制代码 代码示例:
s = "Count, the number of spaces."
print s.count(" ")
x = "I like to program in Python"
print x.count("i")

二、python脚本统计代码行数

python脚本实现代码行数统计

bash shell统计文件行数的例子http://www.jb200.com/article/31317.html

代码:
 

复制代码 代码示例:

#!/usr/bin/python
'''
        File      : count.py
        Author    : Mike
        E-Mail    : Mike_Zhang@live.com
'''
import sys,os
extens = [".c",".cpp",".hpp",".h"]
linesCount = 0
filesCount = 0
def funCount(dirName):
    global extens,linesCount,filesCount
    for root,dirs,fileNames in os.walk(dirName):
        for f in fileNames:
            fname = os.path.join(root,f)
            try :
                ext = f[f.rindex('.'):]
                if(extens.count(ext) > 0):
                    print 'support'
                    filesCount += 1
                    print fname
                    l_count = len(open(fname).readlines())
                    print fname," : ",l_count
                    linesCount += l_count
                else:
                    print ext," : not support"
            except:
                print "Error occur!"
                pass

if len(sys.argv) > 1 :
    for m_dir in sys.argv[1:]:       
        print m_dir
        funCount(m_dir)
else :
    funCount(".")       
   
print "files count : ",filesCount
print "lines count : ",linesCount
raw_input("Press Enter to continue")

使用方法
1、针对本目录
./count.py

2、统计多个目录
./count.py /tmp ~

运行效果:
python统计字符串字符出现次数