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设计】。

相关文章

Tesserocr库的正确安装方式

Tesserocr库的正确安装方式

win10,直接使用 pip install tesserocr 的命令 如果输出如下错误提示: tesserocr.cpp(596): fatal error C1083: 无法打...

Python实现查找二叉搜索树第k大的节点功能示例

Python实现查找二叉搜索树第k大的节点功能示例

本文实例讲述了Python实现查找二叉搜索树第k大的节点功能。分享给大家供大家参考,具体如下: 题目描述 给定一个二叉搜索树,找出其中第k大的节点 就是一个中序遍历的过程,不需要额外的...

使用Selenium破解新浪微博的四宫格验证码

使用Selenium破解新浪微博的四宫格验证码

在我们爬虫的时候经常会遇到验证码,新浪微博的验证码是四宫格形式。 可以采用模板验证码的破解方式,也就是把所有验证码的情况全部列出来,然后拿验证码的图片和这所有情况中的图片进行对比,然后获...

PyCharm 2019.3发布增加了新功能一览

PyCharm 2019.3发布增加了新功能一览

Python的IDE(Integrated Development Environment 集成开发环境)非常多,如:VS Code、Sublime、NotePad、Python自带编辑...

python实现apahce网站日志分析示例

维护脚本一例,写得有点乱,只是作为一个实例,演示如何快速利用工具快速达到目的:应用到:shell与python数据交互、数据抓取,编码转换 复制代码 代码如下:#coding:utf-8...