python 文本单词提取和词频统计的实例

yipeiwu_com6年前Python基础

这些对文本的操作经常用到, 那我就总结一下。 陆续补充。。。

操作:

strip_html(cls, text) 去除html标签

separate_words(cls, text, min_lenth=3) 文本提取

get_words_frequency(cls, words_list) 获取词频

源码:

class DocProcess(object):

 @classmethod
 def strip_html(cls, text):
  """
   Delete html tags in text.
   text is String
  """
  new_text = " "
  is_html = False
  for character in text:
   if character == "<":
    is_html = True
   elif character == ">":
    is_html = False
    new_text += " "
   elif is_html is False:
    new_text += character
  return new_text

 @classmethod
 def separate_words(cls, text, min_lenth=3):
  """
   Separate text into words in list.
  """
  splitter = re.compile("\\W+")
  return [s.lower() for s in splitter.split(text) if len(s) > min_lenth]

 @classmethod
 def get_words_frequency(cls, words_list):
  """
   Get frequency of words in words_list.
   return a dict.
  """
  num_words = {}
  for word in words_list:
   num_words[word] = num_words.get(word, 0) + 1
  return num_words

以上这篇python 文本单词提取和词频统计的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 限制函数调用次数的实例讲解

如下代码,限制某个函数在某个时间段的调用次数, 灵感来源:python装饰器-限制函数调用次数的方法(10s调用一次) 欢迎访问 原博客中指定的是缓存,我这里换成限制访问次数,异曲同工...

Python cookbook(数据结构与算法)同时对数据做转换和换算处理操作示例

本文实例讲述了Python同时对数据做转换和换算处理操作。分享给大家供大家参考,具体如下: 问题:我们需要调用一个换算函数(例如sum()、min()、max()),但是首先需对数据做转...

Python使用百度api做人脸对比的方法

Python使用百度api做人脸对比的方法

安装SDK: pip install baidu-aip 如果在pycharm里也可以在setting----Project Interpreter---右边绿色加号,输入baid...

Python实现PS滤镜特效之扇形变换效果示例

Python实现PS滤镜特效之扇形变换效果示例

本文实例讲述了Python实现PS滤镜特效之扇形变换效果。分享给大家供大家参考,具体如下: 这里用 Python 实现 PS 滤镜中的一种几何变换特效,称为扇形变换,将图像扭曲成一个扇形...

Python关于excel和shp的使用在matplotlib

Python关于excel和shp的使用在matplotlib

关于excel和shp的使用在matplotlib 使用pandas 对excel进行简单操作 使用cartopy 读取shpfile 展示到matplotlib中 利用s...