1.个人信息
学号:2017035107234
姓名:李梓宁
我的码云仓库地址:https://gitee.com/lzning/word_frequency.git
2.程序分析
(1)读取文件到缓存区
def process_file(dst): # 读文件到缓冲区
try: # 打开文件
txt = open(dst, "r")
except IOError as s:
print (s)
return None
try: # 读文件到缓冲区
bvffer = txt.read()
except:
print ("Read File Error!")
return None
txt.close()
return bvffer
(2)处理缓存区,统计单词频率,修改特殊符号
def process_buffer(bvffer):
if bvffer:
word_freq = {}
# 下面添加处理缓冲区 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
(3)输出频率前十的单词
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)
(4)执行函数
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)
在命令符中输入python word_freq.py Gone_with_the_wind.txt
运行代码
4.性能分析及改进
5总结
实现了对词频统计及其效能分析,执行了多次代码优化,运行速度提升许多.