Python 简易词频统计

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

def read_file(file):
    f= open(file,'r')
    word = f.read()#读取文件
    word = word.split()#生成列表
    word =sorted(word) # 排序
    return word
def result(word):
    sum = 0             #定义一个记录总词数的变量
    for i in word:
        count = word.count(i)#统计每个单词的个数
        sum += count       #统计该文章的总词数
        for t in range(count-1):
            word.remove(i)  #清除统计后的单词
        if ' ' in word:
            word.pop(' ')  # 删除空格
        f=open('C:\\Users\\Administrator\\Desktop\\out.txt','a')
        w ='单词 '+i+' \t'+'出现次数 '+str(count)+'\n'
        f.write(w)#将数据写入文档
    print('本文章共有单词'+str(sum)+'个')
word= read_file('C:\\Users\\Administrator\\Desktop\\in.txt')

def main():               #定义一个主函数
    result(word)
if __name__ == '__main__':
    main()

猜你喜欢

转载自blog.csdn.net/baidu_39241254/article/details/82805882