python结巴分词 词频统计_一个txt文档,已经用结巴分词分完词,怎么用python工具对这个分完词的文档进行计算统计词频,求脚本,非...
匿名用戶
1級
2016-11-03 回答
#!/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)
總結
以上是生活随笔為你收集整理的python结巴分词 词频统计_一个txt文档,已经用结巴分词分完词,怎么用python工具对这个分完词的文档进行计算统计词频,求脚本,非...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python散点图显示数据_Python
- 下一篇: 什么是分布式_终于搞懂分布式锁是什么了