统计词频

具体操作步骤如下:

#统计词频
#1 输入文章
#2 建立统计词频的空字典
#3 对文本的一行统计词频
#4 获取字典数据对
#5 对数据对进行排序
#6 输出结果
#7 Turtle库绘制词频结果图表
 
实现效果如下:
 
 
 
 
实现代码如下:

 
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 * xScale
    y = y * yScale
    drawLine(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 ##############


#对文本的每一行计算统计词频的函数
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
#空格替换标点的函数
def replacePunctuations(line):
    for ch in "~@#$%^&*()_-+=<>?/,.:;{}[]|\'""":
        line = line.replace(ch," ")
    return line

def main():
    #用户输入文件名
    filename = raw_input("enter a filename: ").strip()
    infile = open(filename,"r")
    #建立用于计算词频的字典
    wordCounts = {}
    for line in infile:
        processLine(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(items[i][1]+"\t"+str(items[i][0]))
        data.append(items[i][0])
        words.append(items[i][1])

    infile.close()
    # 根据词频结果绘制柱状图
    turtle.title("词频结果柱状图")
    turtle.setup(900,750,0,0)
    t= turtle.Turtle()
    t.hideturtle()
    t.width(3)
    drawGraph(t)

    turtle.done()

if __name__ == '__main__':
    main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值