统计词频
具體操作步驟如下:
#統(tǒng)計詞頻
#1 輸入文章
#2 建立統(tǒng)計詞頻的空字典
#3 對文本的一行統(tǒng)計詞頻
#4 獲取字典數(shù)據(jù)對
#5 對數(shù)據(jù)對進行排序
#6 輸出結(jié)果
#7 用Turtle庫繪制詞頻結(jié)果圖表 實現(xiàn)效果如下:
實現(xiàn)代碼如下:
import turtle ##全局變量## count = 10 data = [] words = [] yScale = 6 xScale = 30 ################### #################Turtle Start ############# #繪制線段(x1,y1)到(x2,y2) def drawLine(t,x1,y1,x2,y2):t.penup()t.goto(x1,y1)t.pendown()t.goto(x2,y2) #在坐標(x,y)處寫文字 def drawText(t,x,y,text):t.penup()t.goto(x,y)t.pendown()t.write(text) #繪制圖表 def drawGraph(t):#繪制x/y軸線 drawLine(t,0,0,360,0)drawLine(t,0,300,0,0)#x軸:坐標以及描述 for x in range(count):x = x+1 #右移一位,不在原點 drawText(t,x*xScale-4,-20,words[x-1])drawText(t,x*xScale-4,data[x-1]*yScale+10,data[x-1])drawBar(t) #繪制一個柱體 def drawRectangle(t,x,y):x = x * xScaley = y * yScaledrawLine(t, x - 5, 0, x - 5, y)drawLine(t, x - 5, y, x + 5, y)drawLine(t, x + 5, y, x + 5, 0)drawLine(t, x + 5, 0, x - 5, 0) #繪制多個柱體 def drawBar(t):for i in range(count):drawRectangle(t,i+1,data[i]) ###################### Turtle end ############## #對文本的每一行計算統(tǒng)計詞頻的函數(shù) def processLine(line,wordCounts): #wordCounts空字典 #用空格代替標點符號 line = replacePunctuations(line)#從每一行獲取每個詞 words = line.split()for word in words:if word in wordCounts:wordCounts[word] += 1 else:wordCounts[word] = 1 #空格替換標點的函數(shù) def replacePunctuations(line):for ch in "~@#$%^&*()_-+=<>?/,.:;{}[]|\'""":line = line.replace(ch," ")return linedef main():#用戶輸入文件名 filename = raw_input("enter a filename: ").strip()infile = open(filename,"r")#建立用于計算詞頻的字典 wordCounts = {}for line in infile:processLine(line.lower(),wordCounts)#從字典獲取數(shù)據(jù)對 pairs = list(wordCounts.items())# #列表中的數(shù)據(jù)對交換位置,數(shù)據(jù)對排序 items = [[x,y] for [y,x] in pairs]items.sort()# 輸出count個數(shù)詞頻結(jié)果 for i in range(len(items)-1,len(items)-count-1,-1):print(items[i][1]+"\t"+str(items[i][0]))data.append(items[i][0])words.append(items[i][1])infile.close()# 根據(jù)詞頻結(jié)果繪制柱狀圖 turtle.title("詞頻結(jié)果柱狀圖")turtle.setup(900,750,0,0)t= turtle.Turtle()t.hideturtle()t.width(3)drawGraph(t)turtle.done()if __name__ == '__main__':main()
轉(zhuǎn)載于:https://www.cnblogs.com/relievedliu/p/7366970.html
總結(jié)
- 上一篇: 《吓一秒恋人》跟《超时空同居》剧情一样吗
- 下一篇: 求一个妈妈微信网名