Python下使用optparse模块实现对多个文件进行统计【二】

一个取代shell wc -l 命令的python小脚本

 

1.通过python下optparse模块下OptionParser类是新对文件的统计

 

#!/opt/data/ipy/bin/python
#!-*- coding:utf8 -*-
import sys                              #加载sys模块
from optparse import OptionParser       #加载optparse模块
parser = OptionParser(usage="usage: %prog [options] [file1 file2 ...]")                            #实例化对象
parser.add_option("-c", "--char",
dest="characters",
action="store_true",
default=False,
help="Only count characters")
parser.add_option("-w", "--words",
dest="words",
action="store_true",
default=False,
help="Only count words")
parser.add_option("-l", "--lines",
dest="lines",
action="store_true",
default=False,
help="Only count lines")
(options, args) = parser.parse_args()
if not (options.characters or options.words or options.lines):
options.characters, options.words, options.lines = True, True, True
def get_count(init_data):
words=len(init_data.split())
lines=init_data.count("\n")
chars=len(init_data)
return (chars,words,lines)
def print_wc(chars,words,lines,fn):
if options.characters:
print chars,
if options.words:
print words,
if options.lines:
print lines,
print fn
if args:
t_lines,t_words,t_chars = 0,0,0
for fn in args:
f=open(fn)
data=f.read()
init_data=data.strip()
chars,words,lines = get_count(init_data)
t_lines+=lines
t_words+=words
t_chars+=chars
print_wc(chars,words,lines,fn)
print t_chars,t_words,t_lines,"total"
else:
fn="stdin"
data=sys.stdin.read()
init_data=data.strip()
chars,words,lines=get_count(init_data)
print_wc(chars,words,lines,fn)

 

你可能感兴趣的:(python,import)