python 词语频率统计,英语词频统计Python

  python 词语频率统计,英语词频统计Python

  大家好,我是小明。

  上次分享《100毫秒过滤一百万字文本的停用词》,这次分享如何做词频统计。

  当然,我们首先需要准备数据:

  准备数据导入jieba with Open( d:/HDFS/小说/天龙八部. txt ,编码= GB 18030 )as f:text=f . read()with Open( d:/HDFS/小说/人名. txt ,编码= utf-8) as f: for line in f: if line。以(天巴龙不)开头:names=next (f)。split()break for word in names:jieba . add _ word(word)# Load stop words with open( stop list . txt ,encoding= UTF-8-SIG )as f:stop _ words=f . read()。split () stop _ words.extend ([天龙八部, \n , \u3000 ,)See ])stop _ words=set(stop _ words)all _ words=[word for word in cut _ word if len(word)1 and word not in stop _ words]print(len(all _ words),all _ words [:20])结果:

  26435 [天龙,世明,蓝衫,开放,险峰,玉壁上走,月华,吉祥,尤雅, gxdhb ,微步,盛家,]

  word={ } for word in all _ words:word count[word]=word count . get(word,0) 1sorted (wordcount.items(),key=lambda x: x [1],reverse=true) [:10]结果:

  使用计数类进行词频统计:

  从集合导入计数器字数=counter (all _ words)字数. most _ common (10)结果:

  使用熊猫的词频统计:

  Pd.series (all _ words)。value _ counties()。标题(10)结果:

  从上面的结果可以看出,使用集合的Counter类进行计数速度更快,编码也最简单。

  在分词过程中,直接词频统计熊猫只能统计已经切分的词的词频,这里就不做演示了。上面的测试表明,计数器直接计数列表的速度比pyhton native band快,但循环中的性能未知。让我们继续测试。

  首先用原生API直接统计词频并排序:

  % % time word count={ } for word in jieba . cut(text):if len(word)1 and word not in stop _ words:word count[word]=word count . get(word,0)1 print(sorted(word count . items(),key=lambda x: x [1],reverse=true) [:10])结果:

  [(内向列车,2496),(赛义德,2151),( JQDJB ,1633),( YJDDHB ,1301),(武功,1095),(阿子,922),(

  % % time word count=counter()for word in jieba . cut(text):iflen(word)1 and word not in stop _ words:word count[word]=1 print(word count . most _ common(10))结果:

  [(内向火车,2496),(赛义德,2151),( JQDJB ,1633),( YJDDHB ,1301),(武公,1095),(阿子,922),( ( jmdxrz ,871)]壁时:6.21 s你可以看到计数器在循环中计数的时候会慢一点,但是因为Counter类整体性能更好,也容易编写,所以一般用于统计计数。

  总结今天给大家分享了三种词频统计的方法。这一期我也分享了set set和dictionary的基本原理。希望你能学到所学。

  我是小明。下次再见。

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: