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编程中线程的创建与锁的使用

创建线程 创建线程的两种方法: 1,直接调用threading.Thread来构造thread对象,Thread的参数如下: class threading.Thread(group=N...

老生常谈python之鸭子类和多态

一、 什么是多态 <1>一种类型具有多种类型的能力 <2>允许不同的对象对同一消息做出灵活的反应 <3>以一种通用的方式对待个使用的对象 <4&...

python调用webservice接口的实现

python调用webservice接口的实现

使用suds这个第三方模块 from suds.client import Client url = 'http://ip:port/?wsdl' cilent=Client...

pycharm恢复默认设置或者是替换pycharm的解释器实例

pycharm恢复默认设置或者是替换pycharm的解释器实例

Windows 找到下面的路径,然后删掉即可 # Windows Vista, 7, 8, 10:<SYSTEM DRIVE>\Users\<USER ACCOUN...

Python迭代器与生成器基本用法分析

本文实例讲述了Python迭代器与生成器基本用法。分享给大家供大家参考,具体如下: 迭代器 可以进行for循环的数据类型包括以下两种: 1. 集合数据类型比如list,tuple,dic...