使用python画条形统计图
import turtle
'''全局变量'''
amount = 10
words = []
wCounts = []
xPoint = -360
yPoint = -200
'''turtle start'''
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,fontSize=10):
t.penup()
t.goto(x,y)
t.pendown()
t.write(text,font=('微软雅黑',fontSize,),align='center')
def drawRectangle(t,x,y,rWidth):
drawLine(t,x-rWidth,yPoint,x-rWidth,y)
drawLine(t,x-rWidth,y,x rWidth,y)
drawLine(t,x rWidth,y,x rWidth,yPoint)
drawLine(t,x rWidth,yPoint,x-rWidth,yPoint)
def drawBarchart(t):
drawText(t,0,-yPoint-40,"词频统计结果",15)
drawRectangle(t,0,-yPoint,-xPoint)
rWidth = -xPoint/(2*amount)
xScale = -xPoint*2/(amount 1)
yScale = -yPoint/wCounts[0]
for i in range(amount):
i=i 1
x=i*xScale xPoint
y=wCounts[i-1]*yScale yPoint
drawText(t,x,yPoint-20,words[i-1])
drawText(t,x,y 10,wCounts[i-1])
t.begin_fill()
drawRectangle(t,x,y,rWidth)
t.end_fill()
def init():
turtle.title('词频结果柱状图')
turtle.screensize(900,750,"#272727")
t=turtle.Turtle()
t.hideturtle()
t.width(1)
t.color("#EBEBD0","#006030")
drawBarchart(t)
turtle.exitonclick()
'''data Processing'''
def processLine(line,wordamounts):
line = replacePunctuations(line)
words = line.split()
for word in words:
if word in wordamounts:
wordamounts[word] = 1
else:
wordamounts[word] = 1
#空格替换标点
def replacePunctuations(line):
for ch in line:
if ch in "~!@#$%^&*()-_ =<>?/,.:;{}[]|\'\"":
line = line.replace(ch,' ')
return line
def dataProcess(filename):
infile=open(filename,'r',encoding='UTF-8')
wordamounts={}
for line in infile:
processLine(line.lower(),wordamounts)
pairs = list(wordamounts.items())
items = [[x,y]for (y,x) in pairs]
items.sort()
for i in range(len(items)-1,len(items)-amount-1,-1):
print(items[i][1] "\t" str(items[i][0]))
wCounts.append(items[i][0])
words.append(items[i][1])
infile.close()
def main():
filename= input("enter a filename:").strip()
dataProcess(filename)
init()
if __name__ == '__main__':
main()
评论