zoukankan      html  css  js  c++  java
  • 综合练习:词频统计

    综合练习

    词频统计预处理

    1、下载一首英文的歌词或文章

    将所有,.?!’:等分隔符全部替换为空格

    将所有大写转换为小写

    生成单词列表

    生成词频统计

    排序

    排除语法型词汇,代词、冠词、连词

    输出词频最大TOP20

    将分析对象存为utf-8编码的文件,通过文件读取的方式获得词频分析内容。

    f=open("file.txt","r")
    news=f.read()
    f.close()
    sep=''',().;--'''
    exclude={'the','to','and','of','in','for','on','a','when','as','not','with','that'}
    for c in sep:
        news = news.replace(c,'')
    wordList=news.lower().split()
    wordDict={}
    wordSet=set(wordList)-exclude
    for w in wordSet:
        wordDict[w]=wordList.count(w)
    dictList = list(wordDict.items())
    dictList.sort(key=lambda x:x[1],reverse=True)
    for i in range(20):
        print(dictList[i])

    2、下载一长篇中文文章。

    从文件读取待分析文本。

    news = open('gzccnews.txt','r',encoding = 'utf-8')

    安装与使用jieba进行中文分词。

    pip install jieba

    import jieba

    list(jieba.lcut(news))

    生成词频统计

    排序

    排除语法型词汇,代词、冠词、连词

    输出词频最大TOP20(或把结果存放到文件里)

    import jieba
    f = open('gzccnews.txt','r',encoding = 'utf-8')
    story=f.read()
    f.close()
    jieba.add_word('行者')
    jieba.add_word('八戒')
    jieba.add_word('师父')
    sep=''',。‘’“”:;()!?、《》 '''
    exclude={'','\n','','','','',
         '','','','','','','','','',
         '','','','','','','','','',
         '','','','','','','','','',
         '','','','','','','','','',
         '','','','','','','','','',
         '','','','','','','','','',
         '','','','',}
    for c in sep:
        story = story.replace(c,'')
    tem=list(jieba.cut(story))
    wordDict={}
    words=list(set(tem)-exclude)
    for w in range(0,len(words)):
        wordDict[words[w]]=story.count(str(words[w]))
    dictList = list(wordDict.items())
    dictList.sort(key=lambda x:x[1],reverse=True)
    f = open('Count.txt', 'a',encoding="utf-8")
    for i in range(20):
        f.write(dictList[i][0] + ':' + str(dictList[i][1]) + '\n')
    f.close()

  • 相关阅读:
    [HTML]HTML5实现可编辑表格
    [xcode]instruments来检验你的app
    [xcode]Xcode查找函数(方法)调用及被调用
    [工具][windows][visualStudio][充电]番茄助手vaassist常见用法
    [算法]判断一个数是不是2的N次方
    [Ogre]纹理设置
    C++中的类型重定义
    [STL]set/multiset用法详解[自从VS2010开始,set的iterator类型自动就是const的引用类型]
    [Ogre][地形][原创]基于OgreTerrain的地形实现
    PHP模板引擎Smarty内建函数section,sectionelse用法详解
  • 原文地址:https://www.cnblogs.com/932zdb/p/8658551.html
Copyright © 2011-2022 走看看