python提取内容关键词的方法


Posted in Python onMarch 16, 2015

本文实例讲述了python提取内容关键词的方法。分享给大家供大家参考。具体分析如下:

一个非常高效的提取内容关键词的python代码,这段代码只能用于英文文章内容,中文因为要分词,这段代码就无能为力了,不过要加上分词功能,效果和英文是一样的。

# coding=UTF-8

import nltk

from nltk.corpus import brown

# This is a fast and simple noun phrase extractor (based on NLTK)

# Feel free to use it, just keep a link back to this post

# http://thetokenizer.com/2013/05/09/efficient-way-to-extract-the-main-topics-of-a-sentence/

# Create by Shlomi Babluki

# May, 2013

  

# This is our fast Part of Speech tagger

#############################################################################

brown_train = brown.tagged_sents(categories='news')

regexp_tagger = nltk.RegexpTagger(

    [(r'^-?[0-9]+(.[0-9]+)?$', 'CD'),

     (r'(-|:|;)$', ':'),

     (r'\'*$', 'MD'),

     (r'(The|the|A|a|An|an)$', 'AT'),

     (r'.*able$', 'JJ'),

     (r'^[A-Z].*$', 'NNP'),

     (r'.*ness$', 'NN'),

     (r'.*ly$', 'RB'),

     (r'.*s$', 'NNS'),

     (r'.*ing$', 'VBG'),

     (r'.*ed$', 'VBD'),

     (r'.*', 'NN')

])

unigram_tagger = nltk.UnigramTagger(brown_train, backoff=regexp_tagger)

bigram_tagger = nltk.BigramTagger(brown_train, backoff=unigram_tagger)

#############################################################################

# This is our semi-CFG; Extend it according to your own needs

#############################################################################

cfg = {}

cfg["NNP+NNP"] = "NNP"

cfg["NN+NN"] = "NNI"

cfg["NNI+NN"] = "NNI"

cfg["JJ+JJ"] = "JJ"

cfg["JJ+NN"] = "NNI"

#############################################################################

class NPExtractor(object):

    def __init__(self, sentence):

        self.sentence = sentence

    # Split the sentence into singlw words/tokens

    def tokenize_sentence(self, sentence):

        tokens = nltk.word_tokenize(sentence)

        return tokens

    # Normalize brown corpus' tags ("NN", "NN-PL", "NNS" > "NN")

    def normalize_tags(self, tagged):

        n_tagged = []

        for t in tagged:

            if t[1] == "NP-TL" or t[1] == "NP":

                n_tagged.append((t[0], "NNP"))

                continue

            if t[1].endswith("-TL"):

                n_tagged.append((t[0], t[1][:-3]))

                continue

            if t[1].endswith("S"):

                n_tagged.append((t[0], t[1][:-1]))

                continue

            n_tagged.append((t[0], t[1]))

        return n_tagged

    # Extract the main topics from the sentence

    def extract(self):

        tokens = self.tokenize_sentence(self.sentence)

        tags = self.normalize_tags(bigram_tagger.tag(tokens))

        merge = True

        while merge:

            merge = False

            for x in range(0, len(tags) - 1):

                t1 = tags[x]

                t2 = tags[x + 1]

                key = "%s+%s" % (t1[1], t2[1])

                value = cfg.get(key, '')

                if value:

                    merge = True

                    tags.pop(x)

                    tags.pop(x)

                    match = "%s %s" % (t1[0], t2[0])

                    pos = value

                    tags.insert(x, (match, pos))

                    break

        matches = []

        for t in tags:

            if t[1] == "NNP" or t[1] == "NNI":

            #if t[1] == "NNP" or t[1] == "NNI" or t[1] == "NN":

                matches.append(t[0])

        return matches

# Main method, just run "python np_extractor.py"

def main():

    sentence = "Swayy is a beautiful new dashboard for discovering and curating online content."

    np_extractor = NPExtractor(sentence)

    result = np_extractor.extract()

    print "This sentence is about: %s" % ", ".join(result)

if __name__ == '__main__':

    main()

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
Python原始字符串(raw strings)用法实例
Oct 13 Python
python和bash统计CPU利用率的方法
Jul 10 Python
python函数中return后的语句一定不会执行吗?
Jul 06 Python
python解析html提取数据,并生成word文档实例解析
Jan 22 Python
Python使用try except处理程序异常的三种常用方法分析
Sep 05 Python
使用python对文件中的单词进行提取的方法示例
Dec 21 Python
pytorch使用Variable实现线性回归
May 21 Python
python实现得到当前登录用户信息的方法
Jun 21 Python
Django实现web端tailf日志文件功能及实例详解
Jul 28 Python
Python实现语音识别和语音合成功能
Sep 20 Python
Django 项目通过加载不同env文件来区分不同环境
Feb 17 Python
Python实现加密接口测试方法步骤详解
Jun 05 Python
python生成随机mac地址的方法
Mar 16 #Python
python通过线程实现定时器timer的方法
Mar 16 #Python
python每隔N秒运行指定函数的方法
Mar 16 #Python
python实现登陆知乎获得个人收藏并保存为word文件
Mar 16 #Python
Python标准库urllib2的一些使用细节总结
Mar 16 #Python
python实现查询苹果手机维修进度
Mar 16 #Python
python让图片按照exif信息里的创建时间进行排序的方法
Mar 16 #Python
You might like
?算你??的 PHP 程式大小
2006/12/06 PHP
使用PHP生成图片的缩略图的方法
2015/08/18 PHP
php基于CodeIgniter实现图片上传、剪切功能
2016/05/14 PHP
PHP生成推广海报的方法分享
2018/04/22 PHP
Yii 框架控制器创建使用及控制器响应操作示例
2019/10/14 PHP
PHP 进程池与轮询调度算法实现多任务的示例代码
2019/11/26 PHP
7个Javascript地图脚本整理
2009/10/20 Javascript
jQuery学习笔记(2)--用jquery实现各种模态提示框代码及项目构架
2013/04/08 Javascript
jQuery遍历Table应用示例
2014/04/09 Javascript
JavaScript导出Excel实例详解
2014/11/25 Javascript
Javascript中prototype属性实现给内置对象添加新的方法
2015/05/14 Javascript
基于RequireJS和JQuery的模块化编程日常问题解析
2016/04/14 Javascript
jQuery validate插件功能与用法详解
2016/12/15 Javascript
js实现悬浮窗效果(支持拖动)
2017/03/09 Javascript
微信小程序 图片加载(本地,网路)实例详解
2017/03/10 Javascript
MUI 上拉刷新/下拉加载功能实例代码
2017/04/13 Javascript
使用Angular CLI生成路由的方法
2018/03/24 Javascript
详解Angular5 路由传参的3种方法
2018/04/28 Javascript
深入浅析Vue 中 ref 的使用
2019/04/29 Javascript
vue swipeCell滑动单元格(仿微信)的实现示例
2020/09/14 Javascript
Python读取网页内容的方法
2015/07/30 Python
Python3实现将本地JSON大数据文件写入MySQL数据库的方法
2018/06/13 Python
pandas 将list切分后存入DataFrame中的实例
2018/07/03 Python
如何用Python实现简单的Markdown转换器
2018/07/16 Python
python使用MQTT给硬件传输图片的实现方法
2019/05/05 Python
python re.sub()替换正则的匹配内容方法
2019/07/22 Python
Python Mock模块原理及使用方法详解
2020/07/07 Python
使用python批量修改XML文件中图像的depth值
2020/07/22 Python
python空元组在all中返回结果详解
2020/12/15 Python
python中函数返回多个结果的实例方法
2020/12/16 Python
前端使用canvas生成盲水印的加密解密的实现
2020/12/16 HTML / CSS
万得城电器土耳其网站:欧洲第一大电子产品零售商
2016/10/07 全球购物
Linux内核产生并发的原因
2016/11/08 面试题
哈理工毕业生的求职信
2013/12/22 职场文书
2014年应急管理工作总结
2014/11/26 职场文书
MySQL中order by的执行过程
2022/06/05 MySQL