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 相关文章推荐
仅利用30行Python代码来展示X算法
Apr 01 Python
查看Python安装路径以及安装包路径小技巧
Apr 28 Python
分数霸榜! python助你微信跳一跳拿高分
Jan 08 Python
python merge、concat合并数据集的实例讲解
Apr 12 Python
Tensorflow卷积神经网络实例进阶
May 24 Python
pyside+pyqt实现鼠标右键菜单功能
Dec 08 Python
django echarts饼图数据动态加载的实例
Aug 12 Python
python调用Matplotlib绘制分布点图
Oct 18 Python
Python MOCK SERVER moco模拟接口测试过程解析
Apr 13 Python
一文弄懂Pytorch的DataLoader, DataSet, Sampler之间的关系
Jul 03 Python
python爬虫利器之requests库的用法(超全面的爬取网页案例)
Dec 17 Python
python机器学习Github已达8.9Kstars模型解释器LIME
Nov 23 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 正则学习实例
2008/07/30 PHP
PHP中文件缓存转内存缓存的方法
2011/12/06 PHP
php流量统计功能的实现代码
2012/09/29 PHP
基于PHP 面向对象之成员方法详解
2013/05/04 PHP
thinkphp3.x中session方法的用法分析
2016/05/20 PHP
PHP 中使用explode()函数切割字符串为数组的示例
2017/05/06 PHP
PHP简单装饰器模式实现与用法示例
2017/06/22 PHP
JavaScript asp.net 获取当前超链接中的文本
2009/04/14 Javascript
js判断FCKeditor内容是否为空的两种形式
2013/05/14 Javascript
javascript获取下拉列表框当中的文本值示例代码
2013/07/31 Javascript
基于BootStrap栅格栏系统完成网站底部版权信息区
2016/12/23 Javascript
jquery实现侧边栏左右伸缩效果的示例
2017/12/19 jQuery
JS实现的哈夫曼编码示例【原始版与修改版】
2018/04/22 Javascript
Vue-cli@3.0 插件系统简析
2018/09/05 Javascript
Vue 利用指令实现禁止反复发送请求的两种方法
2019/09/15 Javascript
开始着手第一个Django项目
2015/07/15 Python
Python 基础知识之字符串处理
2017/01/06 Python
python基础 range的用法解析
2019/08/23 Python
python打包成so文件过程解析
2019/09/28 Python
python json 递归打印所有json子节点信息的例子
2020/02/27 Python
Python3将ipa包中的文件按大小排序
2020/04/17 Python
基于Python正确读取资源文件
2020/09/14 Python
使用Pytorch搭建模型的步骤
2020/11/16 Python
matplotlib grid()设置网格线外观的实现
2021/02/22 Python
AJAX的全称是什么
2012/11/06 面试题
大学生写自荐信的技巧
2014/01/08 职场文书
给领导的致歉信范文
2014/01/13 职场文书
毕业实习评语
2014/02/10 职场文书
文明餐桌行动实施方案
2014/02/19 职场文书
自愿离婚协议书范文2014
2014/10/12 职场文书
开展批评与自我批评发言稿
2014/10/16 职场文书
监察建议书
2015/02/04 职场文书
幼儿园三八妇女节活动总结
2015/02/06 职场文书
信用卡催款律师函
2015/05/27 职场文书
如何用PHP websocket实现网页实时聊天
2021/05/26 PHP
草系十大最强宝可梦,纸片人上榜,榜首大家最熟悉
2022/03/18 日漫