0x00 前言
好久没发博客了,感觉自己的学习是有点偷懒了。这篇博客也是应专业课程老师作业硬性的要求才发的,希望借这次机会,自己能够再次出发,努力向前吧。
0x01 作业思路
老师在课堂上布置了一个作业,总的来说是对一个源文件进行各方面的字符统计,涉及到了文件和字符读取等操作。具体要求如下:
其实要求很简单,主要就是文件读写操作,又必须是用命令行进行,python中自带的sys库和getopt库可以从命令行中获取参数,所以就果断用python来解决了。
0x02 基本实现过程
基本功能只有三个:统计源文件字符,统计源文件单词,统计源文件行数
所以就只需要写三个功能函数加上一个主函数即可实现其功能。话不多说,直接先贴代码:
#Author:c1e4r
importsysimportgetopt#读取指定文件中的字符数
defread_str(file2):
file= sys.argv[-1]
file1= open(file,'r+')
count=0for line infile1.readlines():
count_line=len(line)
count+=count_line
f= open(file2,'a+')
f.write(file+",字符数:"+str(count)+'\n')
file1.close()
f.close()#读取指定文件中的单词数
defread_word(file2):
file= sys.argv[-1]
file1= open(file,'r+')
count=0for line infile1.readlines():
line= line.replace(","," ")
line= line.replace("."," ")
line= line.replace("!"," ")
line= line.replace("?"," ")
line_word=len(line.split( ))
count+=line_word
f= open(file2,'a+')
f.write(file+",单词数:"+str(count)+'\n')
file1.close()
f.close()#读取指定文件中的行数
defread_line(file2):
file= sys.argv[-1]
file1= open(file,'r+')
count=0for line infile1.readlines():
count+= 1f= open(file2,'a+')
f.write(file+",行数:"+str(count)+'\n')
file1.close()
f.close()defmain():
file= "result.txt"
try:
opts, args= getopt.getopt(sys.argv[1:],"hc:w:l:o:")exceptgetopt.GetoptError:print("test.py [parameter] [input_file_name]")
sys.exit(2)finally:pass
for opt,arg inopts:if opt == '-h':print("test.py -c -w -l -o [input_file_name]") #-h 使用说明
sys.exit()elif opt == "-c":
read_str(file)#-c 返回文件的字符数
elif opt == "-w":
read_word(file)#-w 返回文件的单词总数
elif opt == "-l":
read_line(file)#-l 返回文件的总行数
elif opt == "-o":
file= arg #-o 输出结果的文件
if __name__ == "__main__":
main()
其中稍微有点棘手的是统计文件中的单词数量。因为单词和单词之间不一定是空格(可能是各种标点符号),所以就先把每一行中的标点符号替换成空格,最后用split切割,这样每个单词就被筛选出来了。
for line infile1.readlines():
line= line.replace(","," ")
line= line.replace("."," ")
line= line.replace("!"," ")
line= line.replace("?"," ")
line_word= len(line.split( ))
其他的功能其实就是一个逐行读然后计算的过程,很基础,所以就不做解析了。
0x04 效果截图
程序的效果如下:
后面还要求做个图形化界面。。。我还是老老实实加油学安全吧。