博客
关于我
【Python】词频统计
阅读量:411 次
发布时间:2019-03-06

本文共 1775 字,大约阅读时间需要 5 分钟。

英文文本词频统计

文本处理方法

英文词频统计分为两大步骤:

  • 文本去噪及归一化:首先对文本进行去噪处理,将特殊字符替换为空格,并将所有字符转换为小写。
  • 词频统计:使用字典记录每个单词的出现次数。
  • 代码示例

    #CalHamletV1.pydef getText():    txt = open("hamlet.txt", "r").read()    txt = txt.lower()    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':        txt = txt.replace(ch, " ")    return txthamletTxt = getText()words = hamletTxt.split()counts = {}for word in words:    counts[word] = counts.get(word, 0) + 1items = list(counts.items())items.sort(key=lambda x: x[1], reverse=True)for i in range(10):    word, count = items[i]    print(f"{word:<10}{count:5}")

    运行结果

    以下是英文文本中出现频率最高的前十个单词及其频率:

    • the 1138
    • and 965
    • to 754
    • of 669
    • you 550
    • i 542
    • a 542
    • my 514
    • hamlet 462
    • in 436

    中文文本词频统计

    文本处理方法

    中文词频统计主要包含以下步骤:

  • 分词:使用分词工具对文本进行智能分割,确保单词准确无误。
  • 词频统计:记录每个单词的出现次数。
  • 优化版本

    为了提高统计效率并减少不相关单词的干扰,我们可以对文本进行进一步的优化:

  • 分词:使用分词工具对文本进行智能分割。
  • 词频统计:记录每个单词的出现次数。
  • 去噪处理:将无效单词移除,确保统计结果更具准确性。
  • 以下是优化后的代码示例:

    #CalThreeKingdomsV2.pyimport jiebaexcludes = {"将军", "却说", "荆州", "二人", "不可", "不能", "如此"}txt = open("threekingdoms.txt", "r", encoding='utf-8').read()words = jieba.lcut(txt)counts = {}for word in words:    if len(word) == 1:        continue    elif word == "诸葛亮" or word == "孔明曰":        rword = "孔明"    elif word == "关公" or word == "云长":        rword = "关羽"    elif word == "玄德" or word == "玄德曰":        rword = "刘备"    elif word == "孟德" or word == "丞相":        rword = "曹操"    else:        rword = word    counts[rword] = counts.get(rword, 0) + 1for word in excludes:    del counts[word]items = list(counts.items())items.sort(key=lambda x: x[1], reverse=True)for i in range(10):    word, count = items[i]    print(f"{word:<10}{count:5}")

    运行结果

    以下是中文文本中出现频率最高的前十个单词及其频率:

    • 曹操 953
    • 孔明 836
    • 将军 772
    • 不过 656
    • 玄德 585
    • 关公 510
    • 丞相 491
    • 二人 469
    • 不可 440
    • 荆州 425

    应用案例

    将上述词频统计方法应用到考研英语词汇学习中,可以帮助考生快速掌握高频关键词。通过分析文本中的常见单词,考生可以更有针对性地进行复习和练习。

    转载地址:http://ddtkz.baihongyu.com/

    你可能感兴趣的文章
    python 字典sorted自定义排序,按照key or value排序
    查看>>
    python 字典和列表区别_元组列表和字典的主要区别是什么?
    查看>>
    python 字符串中特定字符替换,截取
    查看>>
    Python 字符串总结
    查看>>
    python 字符串显示中文_Python字符串开头的b"、u"、r"与中文乱码
    查看>>
    Python 字符串的几种拼装方式
    查看>>
    python 存入数据库bigint_python基础_MySQL的bigint类型
    查看>>
    python 学习 面向对象编程
    查看>>
    Python 学习小结
    查看>>
    Python 学习日记第三篇 -- 字典
    查看>>
    Python 学习笔记(一)Data type
    查看>>
    python 安装 easy_install 和 pip 流程
    查看>>
    python 安装echarts
    查看>>
    python 安装opencv及问题解决
    查看>>
    Python 安装程序:“写入文件 C:\Python27\pythonw.exe 时出错“
    查看>>
    Python 安装避坑指南:从入门到进阶
    查看>>
    Python 安装配置详解
    查看>>
    python 实现儿童算术游戏
    查看>>
    python 实现字符串转整型
    查看>>
    Python 实现定时任务的八种方案!
    查看>>