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二分查找算法的递归实现方法。分享给大家供大家参考,具体如下: 这里先提供一段二分查找的代码: def binarySearch(alist, item):...

修改python plot折线图的坐标轴刻度方法

修改python plot折线图的坐标轴刻度方法

修改python plot折线图的坐标轴刻度,这里修改为整数: 代码如下: from matplotlib import pyplot as plt import matplotl...

在Python中编写数据库模块的教程

在一个Web App中,所有数据,包括用户信息、发布的日志、评论等,都存储在数据库中。在awesome-python-app中,我们选择MySQL作为数据库。 Web App里面有很多地...

Kears+Opencv实现简单人脸识别

写在前面:这篇文章也是借鉴了一些前辈的代码和思路写的,代码有些也是复用了别人的。 先说下思路: 1.首先利用Opencv检测出人脸的区域  2.在成功的检测出人脸区域后,将识别...

python 控制语句

1比如python提倡简单实用的思想,它就没有switch语句,如果要实现switch语句的效果 的话可以通过2个方法来写把 (1)通过if elif 语句来实现 if 条件: … el...