python日记Day08——文本词频统计(中英文)

python日记——文本词频统计(中英文)

一、jieba库的基本介绍

  • 中文文本词频统计需要用到第三方库:jieba;
  • jieba库是优秀的中文分词第三方库,需要额外安装;
  • jieba库分词依靠中文词库,确定汉字之间的关联概率;
  • jieba库分词有三种模式:

1、精确模式:把文本精确的切分开,不存在冗余单词;

print(jieba.lcut("时间一定会给你最好的答案"))
#['时间','一定', '会', '给', '你', '最好', '的', '答案']

2、全模式:把文本中所有可能的词语都扫描出来,有冗余;

print(jieba.lcut("时间一定会给你最好的答案",cut_all=True))
#['时间', '一定', '定会', '给', '你', '最好', '的', '答案']

3、搜索引擎模式:在精确模式基础上,对长词再次切分。

print(jieba.lcut_for_search("四川省人民政府"))
#['四川', '人民', '民政', '政府', '四川省', '四川省人民政府']

二、pip安装速度提升

  • 由于jieba是第三方库,因此需要额外安装,在安装时可在命令行环境下通过命令:pip install jieba进行安装,安装过程需要联网;
  • pip在安装时速度较慢,可设置pip通过国内的镜像源进行下载安装;
  • 设置方法,以阿里云镜像源为例:
#临时使用
pip install -i http://mirrors.aliyun.com/pypi/simple package_name
#永久使用
pip config set global.index-url http://mirrors.aliyun.com/pypi/simple
'''
常用下载链接:
阿里云 http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
豆瓣 http://pypi.douban.com/simple/
清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/
中国科学技术大学 http://pypi.mirrors.ustc.edu.cn/simple/
'''

三、英文文本词频统计(hamlet为例)

文本下载:提取码(ncu8)

def getText():
    txt = open("hamlet.txt",'r').read()
    txt = txt.lower()#将文本全部转换为小写形式
    for ch in '!@#$%^&*()_+-,./<>=?[\\]"{|}~':
        txt = txt.replace(ch,'')#将所有的符号全部替换成为空格
    return txt
hamletTxt = getText()
words = hamletTxt.split()
counts = {}#利用字典数据类型对结果进行存储
for word in words:
    counts[word] = counts.get(word,0) +1 #遍历,统计每个单词出现的次数
items = list(counts.items())#取出所有键值对并存入列表中
items.sort(key=lambda x:x[1],reverse=True)#按照词频由大到小的顺序排列
for i in range(10):
    word,count = items[i]
    print("{:<10}{:>5}".format(word,count))

运行效果:
python日记Day08——文本词频统计(中英文)_第1张图片

四、中文文本词频统计(三国演义人物出场次数为例)

代码及说明如下:

import jieba
txt = open("三国演义.txt",'r',encoding='utf-8').read()
excludes = {"将军","却说","荆州","二人","不可",
            "不能","如此","商议","如何","主公",
            "军士","左右","军马","引兵","次日",
            "大喜","天下","东吴"}#通过结果,去掉排在前面但又不是人名的词
words = jieba.lcut(txt)#将文本进行分词并返回一个列表
counts = {}#利用字典数据类型对结果进行存储
for word in words:
    if len(word) ==1:
        continue
    elif word =="诸葛亮" or word == "孔明曰":#将jieba识别出来的“别名”进行统一
        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) +1 #遍历,统计每个单词出现的次数
for word in excludes:
    del counts[word]
items = list(counts.items())#取出所有键值对并存入列表中
items.sort(key=lambda x:x[1],reverse=True)#按照词频由大到小的顺序排列
for i in range(8):
    word,count = items[i]
    print("{:<10}{:>5}".format(word,count))

运行效果:
python日记Day08——文本词频统计(中英文)_第2张图片
本文内容参考于北京理工大学嵩天老师相关课程

你可能感兴趣的:(Python笔记)