nltk(Natural Language Toolkit)是处理文本的利器。

安装

pip install nltk

进入python命令行,键入nltk.download()可以下载nltk需要的语料库等等。

分词

按词语分割(传入句子)

sentence='hello,world!'
tokens=nltk.word_tokenize(sentence)

tokens就是一个分割好的词表,如下:

['hello', ',', 'world', '!']

按句子分割(传入多个句子组成的文档)

text='This is a text. I want to split it.'
sens=nltk.sent_tokenize(text)

sens就是分割好的句子组成的list,如下:

['This is a text.', 'I want to split it.']

词性标注

tags = [nltk.pos_tag(tokens) for tokens in words]
[[('This', 'DT'), ('is', 'VBZ'), ('a', 'DT'), ('text', 'NN'), ('for', 'IN'), ('test', 'NN'), ('.', '.')], [('And', 'CC'), ('I', 'PRP'), ('want', 'VBP'), ('to', 'TO'), ('learn', 'VB'), ('how', 'WRB'), ('to', 'TO'), ('use', 'VB'), ('nltk', 'NN'), ('.', '.')]]

附录:nltk的词性:

  1.  CC      Coordinating conjunction 连接词
  2. CD     Cardinal number  基数词
  3. DT     Determiner  限定词(如this,that,these,those,such,不定限定词:no,some,any,each,every,enough,either,neither,all,both,half,several,many,much,(a) few,(a) little,other,another.
  4. EX     Existential there 存在句
  5. FW     Foreign word 外来词
  6. IN     Preposition or subordinating conjunction 介词或从属连词
  7. JJ     Adjective 形容词或序数词
  8. JJR     Adjective, comparative 形容词比较级
  9. JJS     Adjective, superlative 形容词最高级
  10. LS     List item marker 列表标示
  11. MD     Modal 情态助动词
  12. NN     Noun, singular or mass 常用名词 单数形式
  13. NNS     Noun, plural  常用名词 复数形式
  14. NNP     Proper noun, singular  专有名词,单数形式
  15. NNPS     Proper noun, plural  专有名词,复数形式
  16. PDT     Predeterminer 前位限定词
  17. POS     Possessive ending 所有格结束词
  18. PRP     Personal pronoun 人称代词
  19. PRP$     Possessive pronoun 所有格代名词
  20. RB     Adverb 副词
  21. RBR     Adverb, comparative 副词比较级
  22. RBS     Adverb, superlative 副词最高级
  23. RP     Particle 小品词
  24. SYM     Symbol 符号
  25. TO     to 作为介词或不定式格式
  26. UH     Interjection 感叹词
  27. VB     Verb, base form 动词基本形式
  28. VBD     Verb, past tense 动词过去式
  29. VBG     Verb, gerund or present participle 动名词和现在分词
  30. VBN     Verb, past participle 过去分词
  31. VBP     Verb, non-3rd person singular present 动词非第三人称单数
  32. VBZ     Verb, 3rd person singular present 动词第三人称单数
  33. WDT     Wh-determiner 限定词(如关系限定词:whose,which.疑问限定词:what,which,whose.)
  34. WP      Wh-pronoun 代词(who whose which)
  35. WP$     Possessive wh-pronoun 所有格代词
  36. WRB     Wh-adverb   疑问代词(how where when)

提取关键词

如何对一段话提取关键词呢?主要思想就是先分词,再标词性。

# -*- coding=UTF-8 -*-
import nltk
from nltk.corpus import brown
from nltk.stem import SnowballStemmer
from nltk.corpus import stopwords # 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):
# Split the sentence into singlw words/tokens
def tokenize_sentence(self, sentence):
tokens = nltk.word_tokenize(sentence)
#去除停用词,标点,数字,长度小于2的词
tokens=[w.lower() for w in tokens if(w.isalpha())&(len(w)>1)]#使用tfid,不必去除停用词
#词干提取
stemmer=SnowballStemmer('english')
tokens=[stemmer.stem(w) for w in tokens]
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,sentence): tokens = self.tokenize_sentence(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" or t[1]=="NN":
matches.append(t[0])
return matches

利用这里的extract函数就可以提取文本的关键词。

更多参见nltk官方文档:nltk

nltk处理文本的更多相关文章

  1. 【NLP】Python NLTK获取文本语料和词汇资源

    Python NLTK 获取文本语料和词汇资源 作者:白宁超 2016年11月7日13:15:24 摘要:NLTK是由宾夕法尼亚大学计算机和信息科学使用python语言实现的一种自然语言工具包,其收集 ...

  2. 使用 NLTK 对文本进行清洗,索引工具

    使用 NLTK 对文本进行清洗,索引工具 EN_WHITELIST = '0123456789abcdefghijklmnopqrstuvwxyz ' # space is included in w ...

  3. NLTK实现文本切分

    之前已经了解了使用nltk库,将文本作为参数传入相应函数进行切分的方法,下面看看使用正则表达式如何来进行文本切分. 1. 使用正则表达式切分 1.1 通过RegexpTokenizer 进行切分.先导 ...

  4. 【NLP】干货!Python NLTK结合stanford NLP工具包进行文本处理

    干货!详述Python NLTK下如何使用stanford NLP工具包 作者:白宁超 2016年11月6日19:28:43 摘要:NLTK是由宾夕法尼亚大学计算机和信息科学使用python语言实现的 ...

  5. 【NLP】Python NLTK处理原始文本

    Python NLTK 处理原始文本 作者:白宁超 2016年11月8日22:45:44 摘要:NLTK是由宾夕法尼亚大学计算机和信息科学使用python语言实现的一种自然语言工具包,其收集的大量公开 ...

  6. [转]【NLP】干货!Python NLTK结合stanford NLP工具包进行文本处理 阅读目录

    [NLP]干货!Python NLTK结合stanford NLP工具包进行文本处理  原贴:   https://www.cnblogs.com/baiboy/p/nltk1.html 阅读目录 目 ...

  7. 机器学习之路: python nltk 文本特征提取

    git: https://github.com/linyi0604/MachineLearning 分别使用词袋法和nltk自然预言处理包提供的文本特征提取 from sklearn.feature_ ...

  8. 使用Python中的NLTK和spaCy删除停用词与文本标准化

    概述 了解如何在Python中删除停用词与文本标准化,这些是自然语言处理的基本技术 探索不同的方法来删除停用词,以及讨论文本标准化技术,如词干化(stemming)和词形还原(lemmatizatio ...

  9. 【NLP】Python NLTK 走进大秦帝国

    Python NLTK 走进大秦帝国 作者:白宁超 2016年10月17日18:54:10 摘要:NLTK是由宾夕法尼亚大学计算机和信息科学使用python语言实现的一种自然语言工具包,其收集的大量公 ...

随机推荐

  1. python 爬取豆瓣的美剧

    pc版大概有500条记录,mobile大概是50部,只有热门的,所以少一点 url构造很简单,主要参数就是page_limit与page_start,每翻一页,start+=20即可,tag是&quo ...

  2. Docker + .NET Core(一)

    原文:Docker + .NET Core(一) 前言: 环境:centos7.5 64 位 正文: 拉取 microsoft/dotnet, 安装完毕后执行 docker images 可以看到本地 ...

  3. Crystal Report - 水晶报表导出文件的格式设置

    水晶报表中自带的导出和打印功能用起来确实很方便,只不过有时候需要导出的文件并不需要那么多种类型,在网上找到一些朋友的代码总结了一下,可以通过代码实现自定义导出文件类型 首先需要定义一个枚举: publ ...

  4. 利用WPF建立自己的3d gis软件(非axhost方式)(三)矢量数据显示控制

    原文:利用WPF建立自己的3d gis软件(非axhost方式)(三)矢量数据显示控制 先下载SDK:https://pan.baidu.com/s/1M9kBS6ouUwLfrt0zV0bPew 密 ...

  5. MySQL旧版本ORDER BY 方法

    MySQL 的order by 它涉及到三个参数:A. sort_buffer_size 排序缓存.B. read_rnd_buffer_size 第二次排序缓存.C. max_length_for_ ...

  6. FZU Problem 2062 Suneast & Yayamao

    http://acm.fzu.edu.cn/problem.php?pid=2062 标题效果: 给你一个数n,要求求出用多少个数字能够表示1~n的全部数. 思路: 分解为二进制. 对于一个数n.看它 ...

  7. windows下安装ffmpeg

    一.下载地址: 网址:https://ffmpeg.org/ 选择Windows版本:https://ffmpeg.org/download.html#build-windows 二.解压安装: 下载 ...

  8. unity3d 学习笔记(三)

    工作现场查看: 飞行模式: 按住鼠标右键 w s a d 围绕浏览当前视图, q e 上下浏览. 交模式下无效 需透视图 移动吸附:移动状态(w) ctrl+shif  移动吸附在其它物体上移动 顶点 ...

  9. Spring 的 ApplicationEvent and ApplicationListener

    什么是ApplicationContext? 它是Spring的核心,Context我们通常解释为上下文环境,可是理解成容器会更好些. ApplicationContext则是应用的容器. Sprin ...

  10. Matlab Tricks(二十九) —— 使用 deal 将多个输入赋值给多个输出

    deal:Distribute inputs to outputs: >> [id, name, data] = deal(123, 'zhang', randn(3)) 注意: [Y1, ...