xlwt的下载地址为https://pypi.python.org/pypi/xlwt
一篇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 re
import xlwt
file_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] = 1
else :
word_dict[item] += 1
#将结果以excel形式升序的保存在本地
workbook = xlwt.Workbook()
sheet = workbook.add_sheet('sheet1')
sheet.write(0,0,'Word')
sheet.write(0,1,'Count')
counter = 1
for temp in sorted(word_dict.keys()):
sheet.write(counter,1,word_dict[temp])
sheet.write(counter,0,temp)
counter += 1
workbook.save('new.xls')