跟上一篇文章需求一样:Python计算文件中单词个数,只不过这次使用的是命令行选项与参数解析包argparse来做的。
如果想了解argparse,可以看一下这一篇文章:argparse – Command line option and argument parsing.
功能描述:
在linux命令行运行Python程序WordCount
1.如果只输入单个文件无命令则顺序输出此文件中单词个数、文本行数、字节数。
2.如果输入多个文件无命令则顺序输出这两个文件中单词个数、文本行数、字节数,并且计算每一列的总和total。
3.如1,2所示那样,只不过如果输入带有参数命令的则根据参数命令分别打印相应的文本,命令-w打印单词个数,-l打印文本行数,-c打印文本字节数。
代码如下:
程序名称为ArgsWordCount的缩写,awc.py。
import argparse
import sys
bcount = 0 # 字节数
wcount = 0 # 单词数
lcount = 0 # 行数
btotal = 0 # 字节总数
wtotal = 0 # 单词总数
ltotal = 0 # 行总数
# 创建解释器对象
parser = argparse.ArgumentParser()
# 添加命令
parser.add_argument('-l', action='store_true', dest='lcount', default=False, help='File line count')
parser.add_argument('-w', action='store_true', dest='wcount', default=False, help='File word count')
parser.add_argument('-b', action='store_true', dest='bcount', default=False, help='File word count')
parser.add_argument('i',action='store_true')
parser.add_argument("filepaths", nargs='*')
args = parser.parse_args(sys.argv[1:])
args = parser.parse_args()
# 文件名
IMG = args.filepaths
# 读取文件
for i in IMG:
if ".txt" in i:
file = open(i, 'r')
text = file.read()
file.close()
# 计算字节数
bcount = len(text)
# 计算单词数
wcount = len(text.split())
# 计算行数
lcount = len(text.split("\n"))
# 字节数总和
btotal = btotal + bcount
# 单词个数总和
wtotal = wtotal + wcount
# 行数总和
ltotal = ltotal + lcount
# 1 flags
if args.bcount and not args.lcount and not args.wcount:
print(bcount,i)
if not args.bcount and args.lcount and not args.wcount:
print(lcount,i)
if not args.bcount and not args.lcount and args.wcount:
print(wcount,i)
# 2 flags
if args.bcount and args.lcount and not args.wcount:
print(bcount,lcount,i )
if args.bcount and args.wcount and not args.lcount:
print(bcount,wcount,i )
if args.lcount and args.wcount and not args.bcount:
print(lcount,wcount,i )
# 3 flags
if args.lcount and args.wcount and args.bcount:
print(lcount,wcount,bcount,i )
# 1 total
if args.bcount and not args.lcount and not args.wcount and btotal != bcount:
print(btotal, "total")
if args.lcount and not args.bcount and not args.wcount and ltotal != lcount:
print(ltotal, "total")
if args.wcount and not args.lcount and not args.bcount and wtotal != wcount:
print(wtotal, "total")
# 2 total
if args.bcount and args.lcount and not args.wcount and btotal != bcount and ltotal != lcount:
print(btotal,ltotal, "total")
if args.bcount and args.wcount and not args.lcount and btotal != bcount and wtotal != wcount:
print(btotal,wtotal, "total")
if args.lcount and args.wcount and not args.bcount and ltotal != lcount and wtotal != wcount:
print(ltotal,wtotal, "total")
# 3 total
if args.lcount and args.wcount and args.bcount and ltotal != lcount and wtotal != wcount and btotal != bcount:
print(ltotal,wtotal,bcount, "total")
运行结果: