您的位置:首页 > 编程语言 > Python开发

python:统计历年英语四六级试卷单词词频

2017-11-27 22:34 1396 查看

python练习题

统计文件夹中历年英语四六级试卷单词词频,并根据单词词频按倒序进行排序。

思路:

首先,遍历放有英语试卷文本文件的文件夹,获取试卷文件名。

import os
def countword(file):
filelist=[]   #储存文件名
wordcounts={}   #储存单词及词频
print "\n*****往年试卷高频词汇******\n"
for f in os.listdir("file"):  #遍历文件夹中的文件
#print f
list.append(f)
filelist1=filelist[1:]    #获取试卷文件名
#print filelist1


然后,遍历每一份试卷,统计单词词频

for paper in filelist1:   #遍历文件
content=open("%s/%s"%(paperfile,paper)).read().strip().split()   #打开并读取试卷
for word in content:
word=word.rstrip('.').rstrip(',').rstrip(':').strip("()")  #去除单词前后的标点符号
if word not in wordcounts:
wordcounts[word]=1
else:
wordcounts[word]+=1


最后,将单词和词频按照词频倒序排序

new_wordcounts=sorted(wordcounts.iteritems(),key=lambda v:v[1],reverse=True)   #v[1]为键值排序,v[0]为键排序,
#生成的是以元组为元素的列表
for i in  new_wordcounts:
print i
return i
paperfile="/home/ds/notebooks/lesson1/cet"
countword(paperfile)    #调用函数


运行结果如下:



技术小白的个人实践,其他小伙伴有更好更简洁的代码,希望多多指教
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: