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

    综合练习

    词频统计预处理

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

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

    将所有大写转换为小写

    生成单词列表

    生成词频统计

    排序

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

    输出词频最大TOP20

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

    f=open('text.text','r')
    
    
    new=f.read()
    f.close()
    
    sep='''.,?!'":'''
    exclude={'the','and','of','to'}
    for c in sep:
        new=new.replace(c,' ')
    wordList=new.lower().split()
    
    wordDisct={}
    
    
    wordSet=set(wordList)-exclude
    for w in wordSet:
        wordDisct[w]=wordList.count(w)
    
    dictList=list(wordDisct.items())
    dictList.sort(key=lambda x:x[1], reverse=True)
    
    for c in range(20):
        print(c,dictList[c]);

    2.中文词频统计

    下载一长篇中文文章。

    从文件读取待分析文本。

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

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

    pip install jieba

    import jieba

    list(jieba.lcut(news))

    生成词频统计

    排序

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

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

    import jieba
    
    # 打开文件
    file = open("zwwz", 'r', encoding="utf-8")
    notes = file.read();
    file.close();
    
    # 替换标点符号
    sep = ''':。,?!;∶ ...“”'''
    for i in sep:
     notes = notes.replace(i, ' ');
    
    notes_list = list(jieba.cut(notes));
    
    # 排除单词
    exclude = [' ', '
    ','', '', '']
    
    # 方法②,遍历列表
    notes_dict = {}
    for w in notes_list:
     notes_dict[w] = notes_dict.get(w, 0) + 1
    
    # 排除不要的单词
    for w in exclude:
     del (notes_dict[w]);
    
    for w in notes_dict:
     print(w, notes_dict[w])
    
    # 降序排序
    dictList = list(notes_dict.items())
    dictList.sort(key=lambda x: x[1], reverse=True);
    print(dictList)
    
    # 输出词频最大TOP20
    for i in range(20):
     print(dictList[i])
    
    # 把结果存放到文件里
    outfile = open("top20.txt", "a")
    for i in range(20):
     outfile.write(dictList[i][0] + " " + str(dictList[i][1]) + "
    ")
    outfile.close();

  • 相关阅读:
    8.移动和重命名文件
    7.复制文件和目录
    22.变基
    21.拉取&删除远程分支
    程序员必备课程——网络编程入门
    正则表达式——Java程序员懂你
    编程语言的基础——搞定JavaIO
    需加装饰——装饰模式
    结合提供者模式解析Jenkins源码国际化的实现
    算法族的集中管理——策略模式
  • 原文地址:https://www.cnblogs.com/wwc000/p/8658325.html
Copyright © 2011-2022 走看看