详细题目在https://github.com/Yixiaohan/show-me-the-code上。此次是0004题,统计一个英文纯文本文件中单词出现的个数。总的想法是读文件,将其余字符过滤,使用字典结构来存储结果,最后将结果保存到本地的Excel文件中
参考资料:
一篇Python正则表达式的指南http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html
一篇python操作Excel读写的博客http://blog.sina.com.cn/s/blog_63f0cfb20100o617.html
# -*- coding: utf-8 -*-import reimport xlwtfile_addr = 'word.txt'#使用正则表达式将英文字母外所有字符替换为空格,然后使用split函数将其切割为一个英文单词列表with open(file_addr, 'r') as file:word = re.sub(r'[^a-zA-Z]',' ',unicode(file.read().split()))word = word.split()#将单词变为小写,使用字典来计算单词出现次数word_dict = {}for item in word:item = item.lower()if item not in word_dict:word_dict[item] = 1else :word_dict[item] += 1#将结果以excel形式升序的保存在本地workbook = xlwt.Workbook()sheet = workbook.add_sheet('sheet1')sheet.write(0,0,'Word')sheet.write(0,1,'Count')counter = 1for temp in sorted(word_dict.keys()):sheet.write(counter,1,word_dict[temp])sheet.write(counter,0,temp)counter += 1workbook.save('new.xls')
