做一个词频统计程序,该程序具有以下功能 基本要求: (1)可导入任意英文文本文件 (2)统计该英文文件中单词数和各单词出现的频率(次数),并能将单词按字典顺序输出。 (3)将单词及频率写入文件。

import  re

#读取文件信息
filename="word.txt"
f=open(filename,'r')
artical=f.read()
f.close()

#将文本中的所有英文单词筛选出来 去掉标点和其他文本符号  并且将单词都小写保存在数组List中
List=[]
word=re.findall('[a-zA-Z]+',artical)
for i in word:
    List.append(i.lower())
print(List)

#统计单词数目
print(List.__len__())

#统计各个单词出现的频率,并且按照字典顺序输出并将内容写入文件中
f=open("result.txt",'w')
List=sorted(List)
i=0;
for i in range(0,List.__len__()-1):
    count=List.count(List[i])
    if(List[i]!=List[i+1]):
        print(List[i]+"  "+str(count)+"\n")
        f.write(List[i]+"  "+str(count)+"\n")

猜你喜欢

转载自blog.csdn.net/qq_39621439/article/details/82811366