一个txt文档,已经用结巴分词分完词,怎么用python工具对这个分完词的文档进行计算统计词频,求脚本,非

常感谢

#!/usr/bin/env python3
#-*- coding:utf-8 -*-

import os,random

#假设要读取文件名为aa,位于当前路径
filename='aa.txt'
dirname=os.getcwd()
f_n=os.path.join(dirname,filename)
#注释掉的程序段,用于测试脚本,它生成20行数据,每行有1-20随机个数字,每个数字随机1-20
'''
test=''
for i in range(20):
    for j in range(random.randint(1,20)):
        test+=str(random.randint(1,20))+' '
    test+='\n'
with open(f_n,'w') as wf:
    wf.write(test)
'''
with open(f_n) as f:
    s=f.readlines()

#将每一行数据去掉首尾的空格和换行符,然后用空格分割,再组成一维列表
words=[]
for line in s:
    words.extend(line.strip().split(' '))

#格式化要输出的每行数据,首尾各占8位,中间占18位
def geshi(a,b,c):
    return alignment(str(a))+alignment(str(b),18)+alignment(str(c))+'\n'
#中英文混合对齐 ,参考http://bbs.fishc.com/thread-67465-1-1.html ,二楼
#汉字与字母 格式化占位 format对齐出错 对不齐 汉字对齐数字 汉字对齐字母 中文对齐英文
#alignment函数用于英汉混合对齐、汉字英文对齐、汉英对齐、中英对齐
def alignment(str1, space=8, align = 'left'):
    length = len(str1.encode('gb2312'))
    space = space - length if space >=length else 0
    if align in ['left','l','L','Left','LEFT']:
        str1 = str1 + ' ' * space
    elif align in ['right','r','R','Right','RIGHT']:
        str1 = ' '* space +str1
    elif align in ['center','c','C','Center','CENTER','centre']:
        str1 = ' ' * (space //2) +str1 + ' '* (space - space // 2)
    return str1

w_s=geshi('序号','词','频率')
#由(词,频率)元组构成列表,先按频率降序排序,再按词升序排序,多级排序,一组升,一组降,高级sorted
wordcount=sorted([(w,words.count(w)) for w in set(words)],key=lambda l:(-l[1],l[0]))
#要输出的数据,每一行由:序号(占8位)词(占20位)频率(占8位)+'\n'构成,序号=List.index(element)+1
for (w,c) in wordcount:    
    w_s+=geshi(wordcount.index((w,c))+1,w,c)
#将统计结果写入文件ar.txt中
writefile='ar.txt'
w_n=os.path.join(dirname,writefile)
with open(w_n,'w') as wf:
    wf.write(w_s)

温馨提示:答案为网友推荐,仅供参考
相似回答