import turtle
from turtle import *
#y轴显示放大倍数,刻度值小
yscale=6
#x轴显示放大倍数,刻度值大
xscale = 30
#设置查询出来的最大十条记录
count=10
#词频数组,作为y轴数据
data=[]
#下标数组,作为x轴的下标
words=[]
def proccessLine(line,wordcounts):
newline=replacedouhao(line)
words=newline.split();
for i in words:
if i in wordcounts:
wordcounts[i]+=1
else:
wordcounts[i]=1
def replacedouhao(line):
for ch in line:
if ch in “~@#$%^&()_-+=<>?/,.:;{}[]|’""":
line=line.replace(ch,"") #将每一行里的一些特殊符号都变成空格,因为因为字母里一般是空格区分一个单词
return line
def drawGraph(t):
#绘制x/y轴线
drawLine(t,0,0,360,0)
drawLine(t,360,0,340,6)
drawLine(t,360,0,340,-6) #箭头的绘画
drawLine(t,0,0,0,360)
drawLine(t,0,360,-6,340)
drawLine(t,0,360,6,340) #箭头的绘画
for m in range(count):
m=m+1
drawText(t,mxscale-4,-20,words[m-1]) #这是画下标
drawText(t,m*xscale-4,data[m-1]*yscale+10,data[m-1])#这是画上标
bigbig(t)
#画线的函数
def drawLine(t,x1,y1,x2,y2):
t.penup()
t.goto(x1,y1)
t.pendown()
t.goto(x2,y2)
#绘制文字的函数
def drawText(t,x,y,text):
t.penup()
t.goto(x,y)
t.pendown()
t.write(text)
#绘制柱体的函数
def drawRectangle(t,x,y):
x=(x+1)xscale
y=yyscale
drawLine(t,x-5,0,x-5,y)
drawLine(t,x-5,0,x+5,0)
drawLine(t,x+5,0,x+5,y)
drawLine(t,x-5,y,x+5,y)
def bigbig(t):
for i in range(count):
drawRectangle(t,i,data[i])
def main():
englishfile=open(“english.txt”,“r”,encoding=‘UTF-8’)
wordcounts={} #声明一个空字典
for line in englishfile:
proccessLine(line.lower(),wordcounts)
pairs=list(wordcounts.items())#键值对{字母:个数}变成列表(字母,个数)
items=[[x,y]for (y,x) in pairs] #(字母,个数) 变成:(个数,字母)
items.sort() #交换列表数据项排序,默认为升序
#输出count个数词频结果
for i in range(len(items)-1,len(items)-count-1,-1): #开始,结束,步长,这里变成从大到小获取的数据,反过来取数据
print(str(items[i][0])+”\t"+str(items[i][1]))
data.append(items[i][0])
words.append(items[i][1])
englishfile.close()
turtle.title(‘词频结果柱状图’)
turtle.setup(900,750,0,0)
t=Turtle()
t.width(3)
drawGraph(t)
turtle.done()
if name == “main”:
main()