逐步实现python版wc命令
#!/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))
while True:
....: data = fd.readline()
....: if not data:
....: break
....: print(data)
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)
#!/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的变量更多而已
#!/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())
#!/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()
#!/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()
逐步实现python版wc命令的更多相关文章
- 使用 python 实现 wc 命令程序的基本功能
这里使用了 python 的基本代码实现了 Linux 系统下 wc 命令程序的基本功能. #!/usr/bin/env python #encoding: utf-8 # Author: liwei ...
- Python模拟wc命令(软件测试第二次作业)
Python实现字符,单词,行,代码行,空行及可视化 Gitee项目地址:https://gitee.com/biubiubiuLYQ/word_and_character_statistics 一. ...
- 作业(二)—python实现wc命令
Gitee地址:https://gitee.com/c1e4r/word-count(为什么老师不让我们用github) 0x00 前言 好久没发博客了,感觉自己的学习是有点偷懒了.这篇博客也是应专业 ...
- python学习:简单的wc命令实现
#!/usr/bin/python import sys import os try: fn = sys.argv[1] except IndexError: print &q ...
- 【原】Learning Spark (Python版) 学习笔记(一)----RDD 基本概念与命令
<Learning Spark>这本书算是Spark入门的必读书了,中文版是<Spark快速大数据分析>,不过豆瓣书评很有意思的是,英文原版评分7.4,评论都说入门而已深入不足 ...
- Learning Spark (Python版) 学习笔记(一)----RDD 基本概念与命令
<Learning Spark>这本书算是Spark入门的必读书了,中文版是<Spark快速大数据分析>,不过豆瓣书评很有意思的是,英文原版评分7.4,评论都说入门而已深入不足 ...
- Spark入门(Python版)
Hadoop是对大数据集进行分布式计算的标准工具,这也是为什么当你穿过机场时能看到”大数据(Big Data)”广告的原因.它已经成为大数据的操作系统,提供了包括工具和技巧在内的丰富生态系统,允许使用 ...
- 【原】Learning Spark (Python版) 学习笔记(三)----工作原理、调优与Spark SQL
周末的任务是更新Learning Spark系列第三篇,以为自己写不完了,但为了改正拖延症,还是得完成给自己定的任务啊 = =.这三章主要讲Spark的运行过程(本地+集群),性能调优以及Spark ...
- 【Python】《大话设计模式》Python版代码实现
<大话设计模式>Python版代码实现 上一周把<大话设计模式>看完了,对面向对象技术有了新的理解,对于一个在C下写代码比较多.偶尔会用到一些脚本语言写脚本的人来说,很是开阔眼 ...
随机推荐
- 在Kotlin编写RecyclerView适配器(KAD 16)
作者:Antonio Leiva 时间:Mar 14, 2017 原文链接:https://antonioleiva.com/recyclerview-adapter-kotlin/ 通过创建Recy ...
- SpringBoot:工厂模式实现定时任务可配置
pringBoot:工厂模式实现定时任务可配置 需要:使用springboot,实现定时任务可配置. 定时任务可在代码中写死,在配置文件中配置,这些都不能实现定时任务在服务器不重启的情况下可配置. 为 ...
- 学习bash——通配符与特殊符号
一.通配符 这是bash操作环境中一个非常有用的功能,这让我们使用bash处理数据就更方便了. 常用通配符如下: 符号 意义 * 代表0个到无穷多个任意字符 ? 代表一个任意字符 [] 代表一定有一个 ...
- DP入门(1)——数字三角形问题
一.问题描述 如上图所示,有一个由非负整数组成的三角形,第一行只有一个数,除了最下行之外每个数的左下方和右下方各有一个数.现请你在此数字三角形中寻找一条从首行到最下行的路径,使得路径上所经过的数字之和 ...
- 并查集——poj1703(带权并查集入门)
传送门:Find them, Catch them 题意:警察抓获N个罪犯,这些罪犯只可能属于两个团伙中的一个,现在给出M个条件(D a b表示a和b不在同一团伙),对于每一个询问(A a b)确定a ...
- lintcode-59-最接近的三数之和
59-最接近的三数之和 给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和. 注意事项 只需要返回三元组之和,无需返回三元组本身 样例 例如 S = ...
- lintcode-101-删除排序数组中的重复数字 II
101-删除排序数组中的重复数字 II 跟进"删除重复数字": 如果可以允许出现两次重复将如何处理? 样例 标签 数组 两根指针 脸书 思路 参照上一篇博客lintcode-100 ...
- lintcode-74-第一个错误的代码版本
74-第一个错误的代码版本 代码库的版本号是从 1 到 n 的整数.某一天,有人提交了错误版本的代码,因此造成自身及之后版本的代码在单元测试中均出错.请找出第一个错误的版本号. 你可以通过 isBad ...
- Activiti工作流(二)——入门Demo及数据库
上篇博客简单介绍了Activiti流程图的使用,这篇博客我们就根据这个流程图来完成这一个流程. 下图是Activiti的系统服务结构图,在后面的流程中,我们会用到其中的功能组件,如Repositor ...
- 【Autofac】- 创建的类的生命周期
1.InstancePerDependency 对每一个依赖或每一次调用创建一个新的唯一的实例.这也是默认的创建实例的方式. 官方文档解释:Configure the component so tha ...