zoukankan      html  css  js  c++  java
  • 文本词频统计

    文本词频统计

    一、 纯英文文本词频统计

    • 英文文本:Hamet 分析词频
    http://www.chenyoude.com/预科班/hamlet.txt
    

    问题分析:

    • 文本去噪及归一化
    • 使用字典表达词频

    实现代码

    # 读取文件
    t = open(r'C:Users青柠Desktop预科第六天factory','r').read()
    # 将读取文件小写化并以空格分割
    t = t.lower().split(' ')
    
    word = {} # 使用字典存储读入的数据
    for i in t:
        if i not in word:
            word[i] = 1
        else:
            word[i] +=1
    
    # 使用函数取出单词出现的次数 方便排序
    def func(i):
        return i[1]
    list = list(word.items()) # 将字典转化为元组(元组可排序)
    list.sort(key = func) # 将函数取出来的次数进行初始排序
    list.reverse() # 反转,降序排列
    
    for i in list[0:10]: # 规格化输出
        print(f'{i[0]:^7}{i[1]^5}')
    

    输出结果:

    the  786
    and  593
    of   522
    to   505
     a   381
    my   370
    in   325
    you  319
     i   294
    his  238
    

    二、纯中文文本词频统计

    • 中文文本:《三国演义》 分析人物
    http://www.chenyoude.com/预科班/threekingdoms.html
    

    问题分析

    • 中文文本分词
    • 使用字典表达词频

    实现代码

    # 使用结巴库进行中文文本断句
    import jieba
    t = open(r'C:Users青柠Desktop预科第六天sanguo','r',encoding='utf-8').read()
    t = jieba.lcut(t)
    
    word = {}
    for i in t:
        # 进行文本去噪,不需要打印的去除
        if len(i) == 1:
            continue
        if i in {"将军", "却说", "荆州", "二人", "不可", "不能", "如此", "商议"}:
            continue
        if '曰' in i:
            continue
        if i in word:
            word[i] += 1
        else:
            word[i] = 1
    
    def func(i):
        return i[1]
    list = list(word.items())
    list.sort(key=func)
    list.reverse()
    for i in list[0:10]:
        print(i[0],i[1])
    

    输出结果:

    曹操 953
    孔明 836
    玄德 585
    关公 510
    丞相 491
    张飞 358
    如何 338
    主公 331
    军士 317
    吕布 300
    
  • 相关阅读:
    HDU 2013(递归)
    紫书搜索 习题7-6 UVA
    紫书搜索 习题7-4 UVA
    紫书搜索 习题7-3 UVA
    紫书搜索 习题7-2 UVA
    紫书搜索 习题7-1 UVA
    紫书搜索 例题7-10 UVA
    紫书搜索 例题7-13 UVA
    紫书搜索 例题7-12 UVA
    紫书搜索 例题7-9 UVA
  • 原文地址:https://www.cnblogs.com/dadazunzhe/p/11213474.html
Copyright © 2011-2022 走看看