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()

  • 相关阅读:
    07 总结ProgressDialog 异步任务
    1. vim 的安装及配置
    debian 源设置 ( apt-get 不能安装)
    在Debian中安装VNC Server
    让BB-Black通过usb0上网
    常用的一些 linux 指令
    Linux下同一目录内文件和目录为什么不能同名?
    beaglebone black 与电脑互传文件(夹)
    永久修改 putty字体大小
    Beaglebone Black的引脚分配
  • 原文地址:https://www.cnblogs.com/932zdb/p/8658551.html
Copyright © 2011-2022 走看看