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

yipeiwu_com5年前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 限制函数执行时间,自己实现timeout的实例

如下所示: # coding=utf-8 import signal import time def set_timeout(num, callback): def wr...

在python中获取div的文本内容并和想定结果进行对比详解

div的内容为: <div style="background-color: rgb(255, 238, 221);" id="status" class="errors">...

解决Scrapy安装错误:Microsoft Visual C++ 14.0 is required...

问题描述 当前环境win10,python_3.6.1,64位。 在windows下,在dos中运行pip install Scrapy报错: building 'twisted.t...

对python3 urllib包与http包的使用详解

urllib包和http包都是面向HTTP协议的。其中urllib主要用于处理 URL,使用urllib操作URL可以像使用和打开本地文件一样地操作。而 http包则实现了对 HTTP协...

python实现从网络下载文件并获得文件大小及类型的方法

本文实例讲述了python实现从网络下载文件并获得文件大小及类型的方法。分享给大家供大家参考。具体实现方法如下: import urllib2 from settings impor...