课后作业3

1)学号:2017035107190

 姓名:李昊

2)

# filename: word_freq.py
# 阅读注释,在所有pass处删除pass,添加代码

from string import punctuation


def process_file(dst): # 读文件到缓冲区
try: # 打开文件
l = open(dst,'r')
except IOError as s:
print (s)
return None
try: # 读文件到缓冲区
bvffer=l.read()
except:
print ("Read File Error!")
return None
l.close()

return bvffer


def process_buffer(bvffer):
if bvffer:
word_freq = {}
# word_freq
for i in bvffer.split():
word1 = i.strip(punctuation + " ")
if word1 in word_freq:
word_freq[word1] += 1
else:
word_freq[word1] = 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]: # 输出 Top 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)

3)最多:l = open(dst,'r')
except IOError as s:
print (s)
return None

最长:sorted_word_freq = sorted(word_freq.items(), key=lambda v: v[1], reverse=True)

4)

5)通过本次作业让我更加了解和熟练python语言。

posted @ 2019-04-07 15:12  (李昊)  阅读(128)  评论(1编辑  收藏  举报