第三次作业

学号:2017*****1050

姓名:丛超

我的仓库代码:https://gitee.com/congchao123/word_frequency/blob/SE1050/word_freq.py

 

代码如下:

from string import punctuation
def process_file(dst):
try:
f = open(dst)
except IOError, s:
print s
return None
try:
bvffer = f.read()
except:
print "Read File Error!"
return None
f.close()
return bvffer

def process_buffer(bvffer):
if bvffer:
word_freq = {}
for item in bvffer.strip().split():
word = item.strip(punctuation+' ')
if word in word_freq.keys():
word_freq[word] += 1
else:
word_freq[word] = 1
return word_freq

def output_result(word_freq):
if word_freq:
sorted_word_freq = sorted(word_freq.items(), key=lambda v: v[1], reverse=True)
for item in sorted_word_freq[:10]:
print item

if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('dst')
args = parser.parse_args()
dst = args.dst
bvffer = process_file(dst)
word_freq = process_buffer(bvffer)
output_result(word_freq)

 

 

 

优化了软件 提升了运行速度

posted @ 2019-04-07 16:21  cc++  阅读(149)  评论(1编辑  收藏  举报