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中装饰器兼容加括号和不加括号的写法详解
Jul 05 Python
Python numpy 常用函数总结
Dec 07 Python
Python判断中文字符串是否相等的实例
Jul 06 Python
Linux下Pycharm、Anaconda环境配置及使用踩坑
Dec 19 Python
pyttsx3实现中文文字转语音的方法
Dec 24 Python
Python基础学习之类与实例基本用法与注意事项详解
Jun 17 Python
python实现两个dict合并与计算操作示例
Jul 01 Python
Python实现队列的方法示例小结【数组,链表】
Feb 22 Python
python GUI库图形界面开发之PyQt5滚动条控件QScrollBar详细使用方法与实例
Mar 06 Python
PyCharm Anaconda配置PyQt5开发环境及创建项目的教程详解
Mar 24 Python
Pycharm无法打开双击没反应的问题及解决方案
Aug 17 Python
python用字节处理文件实例讲解
Apr 13 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中的日期加减方法示例
2014/08/21 PHP
详解WordPress中添加友情链接的方法
2016/05/21 PHP
php实现XML和数组的相互转化功能示例
2017/02/08 PHP
屏蔽网页右键复制和ctrl+c复制的js代码
2013/01/04 Javascript
JavaScript作用域与作用域链深入解析
2013/12/06 Javascript
Javascript编程中几种继承方式比较分析
2015/11/28 Javascript
jQuery中页面返回顶部的方法总结
2016/12/30 Javascript
ionic3 懒加载
2017/08/16 Javascript
Angular4学习教程之HTML属性绑定的方法
2018/01/04 Javascript
Vue SPA单页应用首屏优化实践
2018/06/28 Javascript
vue中提示$index is not defined错误的解决方式
2020/09/02 Javascript
Vue指令实现OutClick的示例
2020/11/16 Javascript
python thread 并发且顺序运行示例
2009/04/09 Python
Python将xml和xsl转换为html的方法
2015/03/10 Python
Python命令行参数解析模块getopt使用实例
2015/04/13 Python
python 读取dicom文件,生成info.txt和raw文件的方法
2019/01/24 Python
python顺序执行多个py文件的方法
2019/06/29 Python
python GUI库图形界面开发之PyQt5信号与槽机制、自定义信号基础介绍
2020/02/25 Python
python+adb命令实现自动刷视频脚本案例
2020/04/23 Python
详解HTML5中的拖放事件(Drag 和 drop)
2016/11/14 HTML / CSS
普天C++笔试题
2016/03/20 面试题
大学生入党思想汇报
2014/01/14 职场文书
《威尼斯的小艇》教学反思
2014/02/17 职场文书
岗位职责风险防控
2014/02/18 职场文书
单位工作证明
2014/10/07 职场文书
学习十八届四中全会精神思想汇报
2014/10/23 职场文书
同意迁入证明模板
2014/10/26 职场文书
2015年前台接待工作总结
2015/05/04 职场文书
医生行业员工的辞职信
2019/06/24 职场文书
如何写一份成功的商业计划书
2019/06/25 职场文书
Python爬虫之爬取二手房信息
2021/04/27 Python
JS Object构造函数之Object.freeze
2021/04/28 Javascript
MySQL系列之六 用户与授权
2021/07/02 MySQL
Javascript 解构赋值详情
2021/11/17 Javascript
利用 Python 的 Pandas和 NumPy 库来清理数据
2022/04/13 Python
SpringBoot使用AOP实现统计全局接口访问次数详解
2022/06/16 Java/Android