【小沐学NLP】Python使用NLTK库的入门教程

31 篇文章 4 订阅

1、简介

NLTK - 自然语言工具包 - 是一套开源Python。 支持自然研究和开发的模块、数据集和教程 语言处理。NLTK 需要 Python 版本 3.7、3.8、3.9、3.10 或 3.11。

NLTK是一个高效的Python构建的平台,用来处理人类自然语言数据。它提供了易于使用的接口,通过这些接口可以访问超过50个语料库和词汇资源(如WordNet),还有一套用于分类、标记化、词干标记、解析和语义推理的文本处理库,以及工业级NLP库的封装器和一个活跃的讨论论坛。

在这里插入图片描述

2、安装

2.1 安装nltk库

The Natural Language Toolkit (NLTK) is a Python package for natural language processing. NLTK requires Python 3.7, 3.8, 3.9, 3.10 or 3.11.

pip install nltk
# or
pip install nltk -i https://pypi.tuna.tsinghua.edu.cn/simple

在这里插入图片描述
可以用以下代码测试nltk分词的功能:

2.2 安装nltk语料库

在NLTK模块中包含数十种完整的语料库,可用来练习使用,如下所示:
古腾堡语料库:gutenberg,包含古藤堡项目电子文档的一小部分文本,约有36000本免费电子书。
网络聊天语料库:webtext、nps_chat
布朗语料库:brown
路透社语料库:reuters
影评语料库:movie_reviews,拥有评论、被标记为正面或负面的语料库;
就职演讲语料库:inaugural,有55个文本的集合,每个文本是某个总统在不同时间的演说.

  • 方法1:在线下载
import nltk
nltk.download()

通过上面命令代码下载,大概率是失败的。
在这里插入图片描述
在这里插入图片描述

  • 方法2:手动下载,离线安装
    github:https://github.com/nltk/nltk_data/tree/gh-pages
    gitee:https://gitee.com/qwererer2/nltk_data/tree/gh-pages
    在这里插入图片描述

  • 查看packages文件夹应该放在哪个路径下
    在这里插入图片描述
    将下载的packages文件夹改名为nltk_data,放在如下文件夹:
    在这里插入图片描述

  • 验证是否安装成功

from nltk.book import *

在这里插入图片描述

  • 分词测试
import nltk
ret = nltk.word_tokenize("A pivot is the pin or the central point on which something balances or turns")
print(ret)

在这里插入图片描述

  • wordnet词库测试

WordNet是一个在20世纪80年代由Princeton大学的著名认知心理学家George Miller团队构建的一个大型的英文词汇数据库。名词、动词、形容词和副词以同义词集合(synsets)的形式存储在这个数据库中。

import nltk
nltk.download('wordnet')
from nltk.corpus import wordnet as wn
from nltk.corpus import brown
print(brown.words())

在这里插入图片描述

3、测试

3.1 分句分词

英文分句:nltk.sent_tokenize :对文本按照句子进行分割
英文分词:nltk.word_tokenize:将句子按照单词进行分隔,返回一个列表

from nltk.tokenize import sent_tokenize, word_tokenize

EXAMPLE_TEXT = "Hello Mr. Smith, how are you doing today? The weather is great, and Python is awesome. The sky is pinkish-blue. You shouldn't eat cardboard."

print(sent_tokenize(EXAMPLE_TEXT))
print(word_tokenize(EXAMPLE_TEXT))

from nltk.corpus import stopwords
stop_word = set(stopwords.words('english'))    # 获取所有的英文停止词
word_tokens = word_tokenize(EXAMPLE_TEXT)      # 获取所有分词词语
filtered_sentence = [w for w in word_tokens if not w in stop_word] #获取案例文本中的非停止词
print(filtered_sentence)

在这里插入图片描述

3.2 停用词过滤

停止词:nltk.corpus的 stopwords:查看英文中的停止词表。

定义了一个过滤英文停用词的函数,将文本中的词汇归一化处理为小写并提取。从停用词语料库中提取出英语停用词,将文本进行区分。

from nltk.tokenize import sent_tokenize, word_tokenize   #导入 分句、分词模块
from nltk.corpus import stopwords                       #导入停止词模块
def remove_stopwords(text):
    text_lower=[w.lower() for w in text if w.isalpha()]
    stopword_set =set(stopwords.words('english'))
    result = [w for w in text_lower if w not in stopword_set]
    return result

example_text = "Stray birds of summer come to my window to sing and fly away. And yellow leaves of autumn,which have no songs,flutter and fall there with a sigh."
word_tokens = word_tokenize(example_text) 
print(remove_stopwords(word_tokens))

在这里插入图片描述

from nltk.tokenize import sent_tokenize, word_tokenize   #导入 分句、分词模块

example_text = "Stray birds of summer come to my window to sing and fly away. And yellow leaves of autumn,which have no songs,flutter and fall there with a sigh."
word_tokens = word_tokenize(example_text) 

from nltk.corpus import stopwords
test_words = [word.lower() for word in word_tokens]
test_words_set = set(test_words)
test_words_set.intersection(set(stopwords.words('english')))
filtered = [w for w in test_words_set if(w not in stopwords.words('english'))] 
print(filtered)

3.3 词干提取

词干提取:是去除词缀得到词根的过程,例如:fishing、fished,为同一个词干 fish。Nltk,提供PorterStemmer进行词干提取。

from nltk.stem import PorterStemmer
from nltk.tokenize import sent_tokenize,word_tokenize
ps = PorterStemmer()
example_words = ["python","pythoner","pythoning","pythoned","pythonly"]
print(example_words)
for w in example_words:
    print(ps.stem(w),end=' ')

在这里插入图片描述

from nltk.stem import PorterStemmer
from nltk.tokenize import sent_tokenize,word_tokenize
ps = PorterStemmer()

example_text = "Stray birds of summer come to my window to sing and fly away. And yellow leaves of autumn,which have no songs,flutter and fall there with a sigh."
print(example_text)
words = word_tokenize(example_text)

for w in words:
    print(ps.stem(w), end=' ')

在这里插入图片描述

from nltk.stem import PorterStemmer
from nltk.tokenize import sent_tokenize, word_tokenize
ps = PorterStemmer()

example_text1 = "Stray birds of summer come to my window to sing and fly away. And yellow leaves of autumn,which have no songs,flutter and fall there with a sigh."
example_text2 = "There little thoughts are the rustle of leaves; they have their whisper of joy in my mind."
example_text3 = "We, the rustling leaves, have a voice that answers the storms,but who are you so silent? I am a mere flower."
example_text4 = "The light that plays, like a naked child, among the green leaves happily knows not that man can lie."
example_text5 = "My heart beats her waves at the shore of the world and writes upon it her signature in tears with the words, I love thee."
example_text_list = [example_text1, example_text2, example_text3, example_text4, example_text5]

for sent in example_text_list:
    words = word_tokenize(sent)
    print("tokenize: ", words)

    stems = [ps.stem(w) for w in words]
    print("stem: ", stems)

在这里插入图片描述

3.4 词形/词干还原

与词干提取类似,词干提取包含被创造出的不存在的词汇,而词形还原的是实际的词汇。

from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
print('cats\t',lemmatizer.lemmatize('cats'))
print('better\t',lemmatizer.lemmatize('better',pos='a'))

在这里插入图片描述

from nltk.stem import WordNetLemmatizer

lemmatizer = WordNetLemmatizer()

print(lemmatizer.lemmatize("cats"))
print(lemmatizer.lemmatize("cacti"))
print(lemmatizer.lemmatize("geese"))
print(lemmatizer.lemmatize("rocks"))
print(lemmatizer.lemmatize("python"))
print(lemmatizer.lemmatize("better", pos="a"))
print(lemmatizer.lemmatize("best", pos="a"))
print(lemmatizer.lemmatize("run"))
print(lemmatizer.lemmatize("run",'v'))

在这里插入图片描述
唯一要注意的是,lemmatize接受词性参数pos。 如果没有提供,默认是“名词”。

  • 时态和单复数
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.stem import PorterStemmer

tokens = word_tokenize(text="All work and no play makes jack a dull boy, all work and no play,playing,played", language="english")
ps=PorterStemmer()
stems = [ps.stem(word)for word in tokens]
print(stems)

from nltk.stem import SnowballStemmer
snowball_stemmer = SnowballStemmer('english')
ret = snowball_stemmer.stem('presumably')
print(ret)

from nltk.stem import WordNetLemmatizer
wordnet_lemmatizer = WordNetLemmatizer()
ret = wordnet_lemmatizer.lemmatize('dogs')
print(ret)

在这里插入图片描述

3.5 同义词与反义词

nltk提供了WordNet进行定义同义词、反义词等词汇数据库的集合。

  • 同义词
from nltk.corpus import wordnet
# 单词boy寻找同义词
syns = wordnet.synsets('girl')
print(syns[0].name())
# 只是单词
print(syns[0].lemmas()[0].name())
# 第一个同义词的定义
print(syns[0].definition())
# 单词boy的使用示例
print(syns[0].examples())

在这里插入图片描述

  • 近义词与反义词
from nltk.corpus import wordnet
synonyms = []  # 定义近义词存储空间
antonyms = []  # 定义反义词存储空间
for syn in wordnet.synsets('bad'):
    for i in syn.lemmas():
        synonyms.append(i.name())
        if i.antonyms():
            antonyms.append(i.antonyms()[0].name())

print(set(synonyms))
print(set(antonyms))

在这里插入图片描述

3.6 语义相关性

wordnet的wup_similarity() 方法用于语义相关性。

from nltk.corpus import wordnet

w1 = wordnet.synset('ship.n.01')
w2 = wordnet.synset('boat.n.01')
print(w1.wup_similarity(w2))

w1 = wordnet.synset('ship.n.01')
w2 = wordnet.synset('car.n.01')
print(w1.wup_similarity(w2))

w1 = wordnet.synset('ship.n.01')
w2 = wordnet.synset('cat.n.01')
print(w1.wup_similarity(w2))

在这里插入图片描述

NLTK 提供多种 相似度计分器(similarity scorers),比如:

  • path_similarity
  • lch_similarity
  • wup_similarity
  • res_similarity
  • jcn_similarity
  • lin_similarity

3.7 词性标注

把一个句子中的单词标注为名词,形容词,动词等。

from nltk.tokenize import sent_tokenize, word_tokenize   #导入 分句、分词模块

example_text = "Stray birds of summer come to my window to sing and fly away. And yellow leaves of autumn,which have no songs,flutter and fall there with a sigh."
word_tokens = word_tokenize(example_text) 

from nltk import pos_tag
tags = pos_tag(word_tokens)
print(tags)

在这里插入图片描述

  • 标注释义如下
| POS Tag |指代 |
| --- | --- |
| CC | 并列连词 |
| CD | 基数词 |
| DT | 限定符|
| EX | 存在词|
| FW |外来词 |
| IN | 介词或从属连词|
| JJ | 形容词 |
| JJR | 比较级的形容词 |
| JJS | 最高级的形容词 |
| LS | 列表项标记 |
| MD | 情态动词 |
| NN |名词单数|
| NNS | 名词复数 |
| NNP |专有名词|
| PDT | 前置限定词 |
| POS | 所有格结尾|
| PRP | 人称代词 |
| PRP$ | 所有格代词 |
| RB |副词 |
| RBR | 副词比较级 |
| RBS | 副词最高级 |
| RP | 小品词 |
| UH | 感叹词 |
| VB |动词原型 |
| VBD | 动词过去式 |
| VBG |动名词或现在分词 |
| VBN |动词过去分词|
| VBP |非第三人称单数的现在时|
| VBZ | 第三人称单数的现在时 |
| WDT |以wh开头的限定词 |
POS tag list:

CC  coordinating conjunction
CD  cardinal digit
DT  determiner
EX  existential there (like: "there is" ... think of it like "there exists")
FW  foreign word
IN  preposition/subordinating conjunction
JJ  adjective   'big'
JJR adjective, comparative  'bigger'
JJS adjective, superlative  'biggest'
LS  list marker 1)
MD  modal   could, will
NN  noun, singular 'desk'
NNS noun plural 'desks'
NNP proper noun, singular   'Harrison'
NNPS    proper noun, plural 'Americans'
PDT predeterminer   'all the kids'
POS possessive ending   parent's
PRP personal pronoun    I, he, she
PRP$    possessive pronoun  my, his, hers
RB  adverb  very, silently,
RBR adverb, comparative better
RBS adverb, superlative best
RP  particle    give up
TO  to  go 'to' the store.
UH  interjection    errrrrrrrm
VB  verb, base form take
VBD verb, past tense    took
VBG verb, gerund/present participle taking
VBN verb, past participle   taken
VBP verb, sing. present, non-3d take
VBZ verb, 3rd person sing. present  takes
WDT wh-determiner   which
WP  wh-pronoun  who, what
WP$ possessive wh-pronoun   whose
WRB wh-abverb   where, when

3.8 命名实体识别

命名实体识别(NER)是信息提取的第一步,旨在在文本中查找和分类命名实体转换为预定义的分类,例如人员名称,组织,地点,时间,数量,货币价值,百分比等。


import nltk
from nltk.tokenize import word_tokenize
from nltk.tag import pos_tag

ex= 'European authorities fined Google a record $5.1 billion on Wednesday for abusing its power in the mobile phone market and ordered the company to alter its practices'

def preprocess(sent):
    sent= nltk.word_tokenize(sent)
    sent= nltk.pos_tag(sent)
    return sent

# 单词标记和词性标注
sent= preprocess(ex)
print(sent)

# 名词短语分块
pattern='NP: {<DT>?<JJ> * <NN>}'
cp= nltk.RegexpParser(pattern)
cs= cp.parse(sent)
print(cs)

# IOB标签
from nltk.chunk import conlltags2tree, tree2conlltags
from pprint import pprint
iob_tagged= tree2conlltags(cs)
pprint(iob_tagged)

# 分类器识别命名实体,类别标签(如PERSON,ORGANIZATION和GPE)
from nltk import ne_chunk
ne_tree= ne_chunk(pos_tag(word_tokenize(ex)))
print(ne_tree)

在这里插入图片描述


import nltk
from nltk.tokenize import word_tokenize
from nltk.tag import pos_tag
from nltk.chunk import conlltags2tree, tree2conlltags

def learnAnaphora():
    sentences = [
        "John is a man. He walks",
        "John and Mary are married. They have two kids",
        "In order for Ravi to be successful, he should follow John",
        "John met Mary in Barista. She asked him to order a Pizza"
    ]

    for sent in sentences:
        chunks = nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent)), binary=False)
        stack = []
        print(sent)
        items = tree2conlltags(chunks)
        for item in items:
            if item[1] == 'NNP' and (item[2] == 'B-PERSON' or item[2] == 'O'):
                stack.append(item[0])
            elif item[1] == 'CC':
                stack.append(item[0])
            elif item[1] == 'PRP':
                stack.append(item[0])
        print("\t {}".format(stack)) 
    
learnAnaphora()

在这里插入图片描述


import nltk

sentence = 'Peterson first suggested the name "open source" at Palo Alto, California'

# 先预处理
words = nltk.word_tokenize(sentence)
pos_tagged = nltk.pos_tag(words)

# 运行命名实体标注器
ne_tagged = nltk.ne_chunk(pos_tagged)
print("NE tagged text:")
print(ne_tagged)

# 只提取这个 树(tree)里的命名实体
print("Recognized named entities:")
for ne in ne_tagged:
    if hasattr(ne, "label"):
        print(ne.label(), ne[0:])

ne_tagged.draw()

在这里插入图片描述
在这里插入图片描述
NLTK 内置的命名实体标注器(named-entity tagger),使用的是宾州法尼亚大学的 Automatic Content Extraction(ACE)程序。该标注器能够识别 组织机构(ORGANIZATION) 、人名(PERSON) 、地名(LOCATION) 、设施(FACILITY)和地缘政治实体(geopolitical entity)等常见实体(entites)。

NLTK 也可以使用其他标注器(tagger),比如 Stanford Named Entity Recognizer. 这个经过训练的标注器用 Java 写成,但 NLTK 提供了一个使用它的接口(详情请查看 nltk.parse.stanford 或 nltk.tag.stanford)。

3.9 Text对象

from nltk.tokenize import sent_tokenize, word_tokenize   #导入 分句、分词模块

example_text = "Stray birds of summer come to my window to sing and fly away. And yellow leaves of autumn,which have no songs,flutter and fall there with a sigh."
word_tokens = word_tokenize(example_text) 
word_tokens = [word.lower() for word in word_tokens]

from nltk.text import Text
t = Text(word_tokens)
print(t.count('and') )
print(t.index('and') )
t.plot(8)

在这里插入图片描述

3.10 文本分类

import nltk
import random
from nltk.corpus import movie_reviews

documents = [(list(movie_reviews.words(fileid)), category)
             for category in movie_reviews.categories()
             for fileid in movie_reviews.fileids(category)]

random.shuffle(documents)

print(documents[1])

all_words = []
for w in movie_reviews.words():
    all_words.append(w.lower())

all_words = nltk.FreqDist(all_words)
print(all_words.most_common(15))
print(all_words["stupid"])

在这里插入图片描述

3.11 其他分类器

  • 下面列出的是NLTK中自带的分类器:
from nltk.classify.api import ClassifierI, MultiClassifierI
from nltk.classify.megam import config_megam, call_megam
from nltk.classify.weka import WekaClassifier, config_weka
from nltk.classify.naivebayes import NaiveBayesClassifier
from nltk.classify.positivenaivebayes import PositiveNaiveBayesClassifier
from nltk.classify.decisiontree import DecisionTreeClassifier
from nltk.classify.rte_classify import rte_classifier, rte_features, RTEFeatureExtractor
from nltk.classify.util import accuracy, apply_features, log_likelihood
from nltk.classify.scikitlearn import SklearnClassifier
from nltk.classify.maxent import (MaxentClassifier, BinaryMaxentFeatureEncoding,TypedMaxentFeatureEncoding,ConditionalExponentialClassifier)
  • 通过名字预测性别

import nltk
from nltk.corpus import names
from nltk import classify

#特征取的是最后一个字母
def gender_features(word):
    return {'last_letter': word[-1]}

#数据准备
name=[(n,'male') for n in names.words('male.txt')]+[(n,'female') for n in names.words('female.txt')]
print(len(name))

#特征提取和训练模型
features=[(gender_features(n),g) for (n,g) in name]
classifier = nltk.NaiveBayesClassifier.train(features[:6000])

#测试
print(classifier.classify(gender_features('Frank')))
print(classify.accuracy(classifier, features[6000:]))

print(classifier.classify(gender_features('Tom')))
print(classify.accuracy(classifier, features[6000:]))

print(classifier.classify(gender_features('Sonya')))
print(classify.accuracy(classifier, features[6000:]))

在这里插入图片描述

  • 情感分析
import nltk.classify.util
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import names


def word_feats(words):
    return dict([(word, True) for word in words])

#数据准备
positive_vocab = ['awesome', 'outstanding', 'fantastic', 'terrific', 'good', 'nice', 'great', ':)']
negative_vocab = ['bad', 'terrible', 'useless', 'hate', ':(']
neutral_vocab = ['movie', 'the', 'sound', 'was', 'is', 'actors', 'did', 'know', 'words', 'not']

#特征提取
positive_features = [(word_feats(pos), 'pos') for pos in positive_vocab]
negative_features = [(word_feats(neg), 'neg') for neg in negative_vocab]
neutral_features = [(word_feats(neu), 'neu') for neu in neutral_vocab]

train_set = negative_features + positive_features + neutral_features

#训练
classifier = NaiveBayesClassifier.train(train_set)

# 测试
neg = 0
pos = 0
sentence = "Awesome movie, I liked it"
sentence = sentence.lower()
words = sentence.split(' ')
for word in words:
    classResult = classifier.classify(word_feats(word))
    if classResult == 'neg':
        neg = neg + 1
    if classResult == 'pos':
        pos = pos + 1

print('Positive: ' + str(float(pos) / len(words)))
print('Negative: ' + str(float(neg) / len(words)))

在这里插入图片描述

3.12 数据清洗

  • 去除HTML标签,如 &
text_no_special_html_label = re.sub(r'\&\w+;|#\w*|\@\w*','',text)
print(text_no_special_html_label)
  • 去除链接标签
text_no_link = re.sub(r'http:\/\/.*|https:\/\/.*','',text_no_special_html_label)
print(text_no_link)
  • 去除换行符
text_no_next_line = re.sub(r'\n','',text_no_link)
print(text_no_next_line)
  • 去除带有$符号的
text_no_dollar = re.sub(r'\$\w*\s','',text_no_next_line)
print(text_no_dollar)
  • 去除缩写专有名词
text_no_short = re.sub(r'\b\w{1,2}\b','',text_no_dollar)
print(text_no_short)
  • 去除多余空格
text_no_more_space = re.sub(r'\s+',' ',text_no_short)
print(text_no_more_space)
  • 使用nltk分词
tokens = word_tokenize(text_no_more_space)
tokens_lower = [s.lower() for s in tokens]
print(tokens_lower)
  • 去除停用词
import re
from nltk.corpus import stopwords

cache_english_stopwords = stopwords.words('english')
tokens_stopwords = [s for s in tokens_lower if s not in cache_english_stopwords]
print(tokens_stopwords)
print(" ".join(tokens_stopwords))

除了NLTK,这几年spaCy的应用也非常广泛,功能与nltk类似,但是功能更强,更新也快,语言处理上也具有很大的优势。

结语

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)っ!!!

  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: Python自然语言处理是指使用Python语言来处理自然语言数据,而NLTK就是Python中最常用的自然语言处理工具之一。在深度学习中,自然语言处理技术已经变得越来越重要,它在处理文本数据、自动翻译、语音识别、情感分析和信息提取等方面发挥着重要作用。 在使用NLTK进行自然语言处理的时候,需要掌握一些基本的用法和技巧。下面介绍一些重要的入门教程: 1.安装NLTK。 首先需要在电脑上安装好PythonNLTK,可以直接使用 pip install nltk 或者从官网下载进行安装。 2.加载数据集。 使用NLTK,可以很方便地预处理自然语言文本数据。可以使用nltk.corpus模块的reuters数据集,通过对文章进行预处理和分类,来预测股市趋势。 3.文本预处理。 自然语言文本数据中有许多瑕疵,如标点符号、停用词等。使用NLTK,可以很方便地进行文本清洗,包括去除标点和停用词。 4.分词分词自然语言处理最基本的步骤之一,需要将一段文本切分成单个词汇。可以使用NLTK的 sent_tokenize()和word_tokenize()方法来实现。 5.词干提取。 同一个单词的不同形态意义相同,需要将它们转化为同一个形式。可以使用NLTK的 PorterStemmer和LancasterStemmer来处理。 6.词性标注。 词性标注是将单个单词标注为他们在句子中扮演的角色,如名词、动词、副词等。可以使用NLTK的pos_tag()方法来实现。 总之,使用NLTK进行自然语言处理,需要掌握一些基本的用法,包括加载数据集、文本预处理、分词、词干提取和词性标注等。掌握这些基本用法,可以进行更深层次的自然语言处理研究。 ### 回答2: Python自然语言处理NLP)是指使用计算机技术处理和分析人类语言的领域。NLP应用广泛,包括情感分析、语音识别、机器翻译、智能问答等等,是近年来非常热门的领域。Python作为一种非常流行的编程语言,也因其简洁易学的特点成为了NLP工程师们的首选语言之一。而在Python NLP中,NLTK是一个非常著名的,提供了很多有用的工具和资源,用于处理自然语言数据。以下简要介绍基于Python中的自然语言处理nltk的用法入门教程。 1. 安装NLTKPython环境下,使用pip安装nltk即可。 2. 下载语料 使用NLTK,可以轻松下载多个语言的语料,包括英语、阿拉伯语、西班牙语等等。可以使用如下代码来下载英语语料: import nltk nltk.download('punkt') 此外,还可以使用其他命令下载更多的资源。 3. 分词 分词NLP中的一个重要任务。NLTK中的word_tokenize方法可以用于将一段文本分成单词。 import nltk text = "This is a sentence." tokens = nltk.word_tokenize(text) print(tokens) 输出内容为 ['This', 'is', 'a', 'sentence', '.'] 4. 词性标注 NLTK还提供了许多方法和资源来进行词性标注。其中,pos_tag方法用于给文本中的每个单词标注词性。标注后的词性可用于后续的文本分析任务中。 import nltk tokens = nltk.word_tokenize("They refuse to permit us to obtain the refuse permit") tagged = nltk.pos_tag(tokens) print(tagged) 输出结果为 [('They', 'PRP'), ('refuse', 'VBP'), ('to', 'TO'), ('permit', 'VB'), ('us', 'PRP'), ('to', 'TO'), ('obtain', 'VB'), ('the', 'DT'), ('refuse', 'NN'), ('permit', 'NN')] 5. 前缀提取 前缀提取是NLP中一种常用的文本处理技术,它将前缀从单词中提取出来,用于相关信息检索。NLTK中的PrefixSpan类可以轻松提取前缀。 import nltk from nltk.corpus import brown from nltk.util import ngrams, pad_sequence from nltk.collocations import PrefixCollocationFinder from nltk.metrics import BigramAssocMeasures text = nltk.Text(brown.words()) prefix_finder = PrefixCollocationFinder(text.tokens, prefix_length=2) top_prefixes = prefix_finder.nbest(BigramAssocMeasures().raw_freq, 10) print(top_prefixes) 输出结果为 [('in', 'the'), ('on', 'the'), ('to', 'the'), ('of', 'the'), ('as', 'a'), ('that', 'the'), ('with', 'the'), ('for', 'the'), ('to', 'be'), ('at', 'the')] 以上就是NLP入门教程nltk使用方法。NLTK为我们提供了丰富的工具和资源,非常方便和高效地处理自然语言数据。希望通过这篇文章的介绍,大家能够轻松入门Python NLP领域。 ### 回答3: Python是一种广泛使用的编程语言,可以在自然语言处理(NLP)领域中发挥巨大作用。NLTK (Natural Language Toolkit),是Python下常用的一种自然语言处理,它提供了很多基本NLP工具和数据集,可以帮助开发人员快速构建自己的NLP应用。 安装nltk: 在前置知识中您已经了解到了如何安装Python和pip,安装nltk其实也非常容易,只需在控制台中输入以下命令即可。 pip install nltk 首先,我们需要安装nltk。在你的监视器上,输入 "import nltk" 以运行。如果没有问题弹出,那么nltk就被成功安装。 现在可以导入所有nltk中的所有元素,并将它们用于文本解析和分析。不过,值得一提的是,nltk不仅仅只包括算法,它还支持不同语言的语料和辅助工具。这篇简单教程将介绍NLTK几个当前常用的功能。 第一步,我们先加载语料nltk.download() 执行上述代码后,会弹出一个下载窗口,在窗口中下载所有需要的子模蜜蜂和相关语料即可。 第二步,我们使用语料: 导入预处理的语料: from nltk.corpus import genesis text = genesis.raw() print(text[:1000]) 在第二行中,我们加载了名为“创世纪”的语料。这个语料包含英语版本的《圣经》,并准备好读取。现在,在第四行中,我们将文本内容存储在名为“text”的新变量中,并在下一行中使用print()函数将前1000个字符输出到屏幕上。 接下来,我们使用正则表达式来分离出所有单词,并将其存储在新的字符串列表words中: from nltk.tokenize import word_tokenize sents = genesis.sents() words = [word_tokenize(sent) for sent in sents] words = [word for sublist in words for word in sublist] print(words[:20]) 此时我们使用nltk.tokenize中的函数word_tokenize来把我们之前的text转化为单词,并分离到sents列表中。 然后使用列表推导式,将sents中的所有字符串合并,并将其存储在名为“words”的新列表中。我们可以使用相同的print()函数来显示前20个单词。 接下来,我们使用NLTK的詞频計算功能来了解在几乎所有课本中都将演示的語料庫分布: from nltk.probability import FreqDist fdist = FreqDist(words) print(fdist) 最后,我们将自己的当前NLTK安装到“C:\Python36\Lib\site-packages\nltk_data”目录中,以确保以后不需要重新下载所有语料。 为此,我们将使用以下代码: import nltk.data nltk.data.path.append("C:\Python36\Lib\site-packages\nltk_data") 我们希望本教程能够帮助您进入自然语言处理(NLP)领域,并掌握入门级的NLTK使用。当然,还有很多更多完整的NLP功能等待您去发掘。总之,希望您可以进一步学习NLP,并创造出更加智能的应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值