python 英语词频统计_Python小程序—文本词频统计

第一部分 英文文本分析词频

以Hamlet文本为例,文本下载链接: https://python123.io/resources/pye/hamlet.txt

jia.gif

jian.gif

#CalHamletV1.py#hamlet文本下载链接:https://python123.io/resources/pye/hamlet.txt

def getText(): #对文本归一化处理(变为小写,特殊字符替换为空格)

txt = open("hamlet.txt","r").read()

txt= txt.lower() #所有字母变为小写

for ch in ‘!"#$%&()*+,-./:;<=>[email protected][\\]^_{|}`~‘:

txt= txt.replace(ch," ") #用空格代替各种特殊字符

returntxt

hamletTxt=getText()

words=hamletTxt.split() #根据空格分隔每一个字母

counts ={}for word inwords:

counts[word]= counts.get(word,0) + 1 #如果键不存在字典中,给出默认值

items = list(counts.items()) #变为列表类型,便于排序操作

items.sort(key=lambda x:x[1], reverse=True) #对第二个元素,从大到小倒排#sort方法小知识:参数lambda用来指定列表中使用哪一个多元选项的列作为排序列,默认的排序是从小到大;reverse设为True,则排序从大到小

for i in range(10): #输出最多的10个单词

word, count =items[i]print("{0:<10}{1:>5}".format(word, count))

CalHamletV1 Code

运行结果:

20191007201018358881.png

第二部分 中文文本分析词频

以《三国演义》文本为例,进行人物出场次数统计,文本下载链接:https://python123.io/resources/pye/threekingdoms.txt

分析:与英文词频分析不同,中文文本分词需要借助第三方库“jieba”,在cmd下输入“pip install jieba”即可安装该库。

jia.gif

jian.gif

#CalThreeKingdomsV1.py

importjieba

txt= open("threekingdoms.txt","r",encoding="utf-8").read()

words=jieba.lcut(txt)

counts={}for word inwords:if len(word) == 1:continue

else:

counts[word]=counts.get(word,0)+ 1items=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))

CalThreeKingdomsV1 Code

运行结果:

20191007201018494629.png

分析结果:发现“孔明”和“孔明曰”是同一个人,分词时却分成两个词组;另外,“二人”、“却说”等并不是人名。因此,需要将词频与任务相关联,面向问题修改程序。

解决思路:1.排除词库;2.名称关联。通过不断显示结果进行优化程序。

jia.gif

jian.gif

#CalThreeKingdomsv2.py

importjieba

txt= open("threekingdoms.txt","r",encoding="utf-8").read()

excludes= {"将军","却说","荆州","二人","不可","不能","如此"}

words=jieba.lcut(txt)

counts={}for word inwords: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 inexcludes:delcounts[word]

items=list(counts.items())

items.sort(key=lambda x:x[1],reverse=True)for i in range(10):

word,count=items[i]print("{0:<10}{1:>5}".format(word,count))

CalThreeKingdomsv2 Code

运行结果:

20191007201018587406.png

接着,需要继续优化程序,把“商议”、“如何”等词语加到排除集合excludes中。

最终最终,可以得出《三国演义》人物出场统计结果为(前20):

曹操、孔明、刘备、关羽、张飞、吕布、赵云、孙权、司马懿、周瑜、袁绍、马超、魏延、黄忠、姜维、马岱、庞德、孟获、刘表、夏侯惇。

原文:https://www.cnblogs.com/HuangYJ/p/11631237.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值