2017**********7025
贾鸿森
def process_file(dst): # 读文件到缓冲区
try: # 打开文件 x = open(dst,"r") except IOError as s: print (s) return None try: # 读文件到缓冲区 bvffer = x.read() except: print ('Read File Error!') return None x.close() return bvffer def process_buffer(bvffer): if bvffer: word_freq = {} # 下面添加处理缓冲区 bvffer代码,统计每个单词的频率,存放在字典word_freq for ch in'"!?;,."': bvffer = bvffer.lower().replace(ch,"") word = bvffer.strip().split() for word in word: word_freq[word] = word_freq.get(word,0)+1return 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)
通过这次作业我掌握了这种查询方法