目录
1. jieba库
-是中文分词的第三方库,需要额外安装
安装方式:(cmd命令行) pip install jieba
-提供三种分词模式,最简单只需掌握一个函数
-利用一个中文词库,确定汉字之间的关联概率
-汉字间概率大的组成词组,形成分词结果
-用户可添加自定义的词组
1.1 jieba分词的三种模式
精确模式:把文本精确的切分开,不存在冗余单词(最常用)
全模式:把文本中所有可能的词语都扫描出来,有冗余
搜索引擎模式:在精确模式的基础上,对长词再次切分
1.2 jieba库常用函数
重点:jieba.lcut(s)
2. 文本词频统计
2.1 "Hamlet英文词频统计”实例
文本来源:https://python123.io/resources/pye/hamlet.txt
编程思路:
① 定义函数对文本进行归一化处理:统一小写,去掉特殊符号换成空格
② 用字典类型对每个单词以及出现的次数机型映射对应
③ 将字典类型转换为列表类型,排序获得当前出现次数最高的单词和次数
④ 对前十位出现的单词和次数进行打印
#CalHamlet
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() #将其变为一个列表
#split默认采用空格将字符串中的信息进行分隔,并以列表形式返回给变量
#采用字典类型表达单词跟出现频率之间的对应关系
counts={}
for word in words:
counts[word]=counts.get(word,0)+1
#字典的.get()用来从字典中获得某一个键对应的值
#若word在字典里面,则返回其次数再加1;若不在,则将其加入字典,赋给其0再加1
#统计完后,将字典类型转变为列表类型
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
#.sort()参数lambda用来指定使用哪一个多元选项的列作为排序列
#默认是从小到大排序,设置reverse=True,返回的排序是从大到小
#按照键值对两个元素的第二个元素进行排序
#输出前十个出现最多的单词及其次数打印
for i in range(10):
word,count=items[i]
print("{0:<10}{1:>5}".format(word,count))
2.2 “《三国演义》人物出场统计”实例
文本来源:https://python123.io/resources/pye/threekingdoms.txt
代码一:
#CalThreekingdoms
import jieba
txt=open("threekingdoms.txt","r",encoding="utf-8").read()
words=jieba.lcut(txt) #形成列表
counts={}
for word in words:
if len(word)==1:
continue
else:
counts[word]=counts.get(word,0)+1
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range(15):
word,count=items[i]
print("{0:<10}{1:>5}".format(word,count))
运行结果:不够准确,出现“二人”“孔明曰”等的统计
代码二:
#CalThreekingdoms
import jieba
txt=open("threekingdoms.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=="孔明曰":
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(15):
word,count=items[i]
print("{0:<10}{1:>5}".format(word,count))
运行结果:还需要根据结果继续修正