您的位置:首页 > 编程语言 > Python开发

逐步实现python版wc命令

2017-05-01 18:36 85 查看
   Python 如何处理管道输入输出   sys.stdin 等于打开了一个文件对象,所有输入的文件都会写入到标准输入文件中(键盘)   sys.stdout 等于打来了一个文件对象,使用.write()把信息写入到标准输出文件中(屏幕)     判断行数:
#!/usr/bin/env python
#_*_ coding:UTF-8 _*_

import sys

#遍历文件对象,并统计行数
def lineCount(f):
n = 0
for i in f:
n += 1
return n

input = sys.stdin
print(lineCount(input))

 

    文件对象的方法:   fd.read() 一次读取所有行,返回字符串   fd.readline() 一次读取一行,返回一个字符串   fd.readlines() 一次读取所有行,返回一个列表,每一行为一个元素   f.write() 写入文件   f.close() 关闭文件(每次打开文件,最好都要手动关闭文件)       利用while循环遍历文件
while True:
....: data = fd.readline()
....: if not data:
....: break
....: print(data)
    文件输出:     sys.stdout.write() 文件写入到标准输出文件中去     print和stdout的区别:   1、print通常是调用一个stdout对象的write方法   2、print会先进行格式转换   3、print会在最后加上换行符    stdout的buffer    通过stdout输出的信息一般会先放在stdout的buffer中,然后等待输出完毕后,一次性输出      这里可以通过两种方式禁止写入buffer     1、sys.stdout.flush(),每次写入buffer,然后强制刷新到文件中     2、python -u scripts.py 执行python解释器的时候,指明不使用buffer,python 2.x 适用 例子:
import sys
import time

for i in range(10):
sys.stdout.write('>') #当然这里加上\n就会一个一个输出,因为sys.stdout是正行正行输出(加\n,就类似于print了)
sys.stdout.flush() #强制i刷新到stdout中去
time.sleep(1)

 

  计算字符:   获取字符数 len(data)   获取单词数 len(data.split()) #以空格分隔,计算有几段   获取行数 data.count('\n') #统计\n出现的次数即可  
#!/usr/bin/env python
import sys
data = sys.stdin.read()
chars = len(data)
words = len(data.split())
lines = data.count('\n')
print('%s %s %s ' % (lines,words,chars)) #传统的字符串替换
print('%(lines)s %(words)s %(chars)s' % locals()) #高级用法,%(key)s,表示格式化关键字替换,后面就需要以字典的方式传入对应的key值,而locals(),表示当前环境下所有的变量和值的字典,所以这里可以进行替换
print('%(lines)s %(words)s %(chars)s' % {'lines':lines,'words':words,'chars':chars}) 这种方法和上面利用locals的方式是一样的,只不过locals的变量更多而已
    没有命令和参数版本的wc:
#!/usr/bin/env python
import sys,os

if len(sys.argv) == 1:
data = sys.stdin.read()
else:
try:
filename = sys.argv[1]
except IndexError as e:
sys.exit('The %s need one parameter' % __file__)

if os.path.exists(filename):
try:
fd = open(filename)
data = fd.read()
fd.close()
except IOError as e:
sys.exit('The Parameter is a file,not a Directory')
else:
sys.exit('The %s is not exist' % filename)

chars = len(data)
words = len(data.split())
lines = data.count('\n')

print('%(lines)s %(words)s %(chars)s' % locals())

 

Python的命令行参数   利用optparse模块,来添加参数和选项  
#!/usr/bin/env python
# Author:Lee Sir

import sys
from optparse import OptionParser #导入optparser模块中的OptionParser类

parser = OptionParser() #实例化一个OptionParser类的对象parser,这里括号里可以添加一些提示信息,用户在执行help时输出(%prog表示脚本名称。例子:%prog [ -c| -l | -d] [file1])
parser.add_option('-c','--char',dest='chars',action='store_true',default=False,help='only user to count chars')

#add_option 表示添加一个选项,-c为选项名称,--char为对应的长选项(可选),dest 表示在程序内引用该变量时的名称,action表示参数后面是否有值(有的话store,没有的话store_true/store_false),default表示该参数默认是添加还是不添加,help(执行-help会显示的内容)
parser.add_option('-w','--word',dest='words',action='store_true',default=False,help='only user to count words')
parser.add_option('-l','--line',dest='lines',action='store_true',default=False,help='only user to count lines')

#parse_args() 会返回一个元组,第一个元素为对象,存储着参数的使用情况,第二个为列表,存储着参数对应的值。(注意,第一个元素为对象,呈现形式很像字典,但不能用字典的方式读取,只能使用option.dest来读写)
options,args = parser.parse_args()

#默认参数,当同时没有-c,-l,-w时,设置这三个参数都是True
if not (options.chars or options.words or options.lines):
options.chars,options.words,options.lines = True,True,True

data = sys.stdin.read()
chars = len(data)
words = len(data.split())
lines = data.count('\n')

if options.chars: #脚本后添加了-c,则option.chars = True
print(chars,end='\t')
if options.words:
print(words,end='\t')
if options.lines:
print(lines)

 

添加判断完善脚本:

  os.Path对文件路径的处理
  os.path.isdir 判断是否是目录
  os.path.isfile 判断是否是文件

#!/usr/bin/env python

import os,sys
from optparse import OptionParser
def opt():
'Get Command line parser'
parser = OptionParser()
parser.add_option('-c','--char',dest='chars',action='store_true',default=False,help='used to count chars')
parser.add_option('-w','--word',dest='words',action='store_true',default=False,help='used to count words')
parser.add_option('-l','--line',dest='lines',action='store_true',default=False,help='used to count lines')
option,args = parser.parse_args()
return option,args

def get_count(data):
'count for lines ,words or chars'
chars = len(data)
words = len(data.split())
lines = data.count('\n')
return lines,words,chars

def print_wc(option,lines,words,chars,filename):
'print lines,words or chars'
if option.lines:
print lines,
if option.words:
print words,
if option.chars:
print chars,
print filename

def main():
'main functions'
option,args = opt()
if not (option.chars or option.words or option.lines):
option.chars , option.words, option.lines = True,True,True
if args:
total_lines,total_words,total_chars = 0, 0, 0
for filename in args:
if os.path.isfile(filename):
with open(filename) as fd:
data = fd.read()
lines,words,chars = get_count(data)
print_wc(option,lines,words,chars,filename)
total_lines += lines
total_words += words
total_chars += chars
elif os.path.isdir(filename):
print >> sys.stderr,'%s is a directory' % filename #利用print写入到文件中去,注意这里仅仅适用于Python 2.x,python3是不支持的(可以用print(i,file=sys.stdout) 或者sys.stdout.write())
else:
sys.exit('%s : No such file or Directory' % filename)
if len(args) > 1:
print_wc(option,total_lines,total_words,total_chars,'total')
else:
data = sys.stdin.read()
filename = ''
lines,words,chars = get_count(data)
print_wc(option,lines,words,chars,filename)

if __name__ == '__main__':
main()

 

逐步实现Python版本的wc命令   添加-n参数,来禁止显示total
#!/usr/bin/env python

import os,sys
from optparse import OptionParser
def opt():
'Get Command line parser'
parser = OptionParser()
parser.add_option('-c','--char',dest='chars',action='store_true',default=False,help='used to count chars')
parser.add_option('-w','--word',dest='words',action='store_true',default=False,help='used to count words')
parser.add_option('-l','--line',dest='lines',action='store_true',default=False,help='used to count lines')
parser.add_option('-n',"--no-total",dest="nototal",action='store_true',default=False,help='not print total')
option,args = parser.parse_args()
return option,args

def get_count(data):
'count for lines ,words or chars'
chars = len(data)
words = len(data.split())
lines = data.count('\n')
return lines,words,chars

def print_wc(option,lines,words,chars,filename):
'print lines,words or chars'
if option.lines:
print lines,
if option.words:
print words,
if option.chars:
print chars,
print filename

def main():
'main functions'
option,args = opt()
if not (option.chars or option.words or option.lines):
option.chars , option.words, option.lines = True,True,True
if args:
total_lines,total_words,total_chars = 0, 0, 0
for filename in args:
if os.path.isfile(filename):
with open(filename) as fd:
data = fd.read()
lines,words,chars = get_count(data)
print_wc(option,lines,words,chars,filename)
total_lines += lines
total_words += words
total_chars += chars
elif os.path.isdir(filename):
print >> sys.stderr,'%s is a directory' % filename
else:
sys.exit('%s : No such file or Directory' % filename)
if len(args) > 1:
if not option.nototal:
print_wc(option,total_lines,total_words,total_chars,'total') else: data = sys.stdin.read() filename = '' lines,words,chars = get_count(data) print_wc(option,lines,words,chars,filename) if __name__ == '__main__': main()

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: