NLTK简单入门和数据清洗

NLTK历史悠久的英文分词工具

# 导入分词模块
from nltk.tokenize import word_tokenize
from nltk.text import Text

input='''
There were a sensitivity and a beauty to her that have nothing to do with looks. She was one to be listened to, whose words were so easy to take to heart.
'''
tokens=word_tokenize(input)
# 打印前5个词
print(tokens[:5])
# 将单词统一转换成小写 There 和 there 应该算同一个词
tokens=[w.lower() for w in tokens]

# 创建一个Text对象
t=Text(tokens)

# 统计某个词的出现的次数
t.count('beauty')

# 计算某个词出现的位置

t.index('beauty')

# 出现最多的前8个词画一个图
# 需要安装matplotlib pip install matplotlib
t.plot(8)

['There', 'were', 'a', 'sensitivity', 'and']

image-20200920174127273

停用词

from nltk.corpus import stopwords

# 打印出所有的停用词支持的语言,我们使用english

stopwords.fileids()
['arabic',
 'azerbaijani',
 'danish',
 'dutch',
 'english',
 'finnish',
 'french',
 'german',
 'greek',
 'hungarian',
 'indonesian',
 'italian',
 'kazakh',
 'nepali',
 'norwegian',
 'portuguese',
 'romanian',
 'russian',
 'spanish',
 'swedish',
 'turkish']
# 打印所有的停用词
stopwords.raw('english').replace('\n',' ')
"i me my myself we our ours ourselves you you're you've you'll you'd your yours yourself yourselves he him his himself she she's her hers herself it it's its itself they them their theirs themselves what which who whom this that that'll these those am is are was were be been being have has had having do does did doing a an the and but if or because as until while of at by for with about against between into through during before after above below to from up down in out on off over under again further then once here there when where why how all any both each few more most other some such no nor not only own same so than too very s t can will just don don't should should've now d ll m o re ve y ain aren aren't couldn couldn't didn didn't doesn doesn't hadn hadn't hasn hasn't haven haven't isn isn't ma mightn mightn't mustn mustn't needn needn't shan shan't shouldn shouldn't wasn wasn't weren weren't won won't wouldn wouldn't "
# 过滤停用词

tokens=set(tokens)

filtered=[w for w in tokens if(w not in stopwords.words('english'))]

print(filtered)
['nothing', 'sensitivity', ',', 'one', 'beauty', 'words', 'heart', 'looks', 'take', 'whose', '.', 'listened', 'easy']

词性标注

# 第一次需要下载相应的组件 nltk.download()
from nltk import pos_tag
pos_tag(filtered)
[('nothing', 'NN'),
 ('sensitivity', 'NN'),
 (',', ','),
 ('one', 'CD'),
 ('beauty', 'NN'),
 ('words', 'NNS'),
 ('heart', 'NN'),
 ('looks', 'VBZ'),
 ('take', 'VB'),
 ('whose', 'WP$'),
 ('.', '.'),
 ('listened', 'VBN'),
 ('easy', 'JJ')]
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开头的限定词

分块

from nltk.chunk import RegexpParser
sentence = [('the','DT'),('little','JJ'),('yellow','JJ'),('dog','NN'),('died','VBD')]
grammer = "MY_NP: {<DT>?<JJ>*<NN>}"
cp = nltk.RegexpParser(grammer) #生成规则
result = cp.parse(sentence) #进行分块
print(result)

result.draw() #调用matplotlib库画出来
(S (MY_NP the/DT little/JJ yellow/JJ dog/NN) died/VBD)



An exception has occurred, use %tb to see the full traceback.


SystemExit: 0

命名实体识别

# 第一次需要下载相应的组件 nltk.download()
from nltk import ne_chunk

input = "Edison went to Tsinghua University today."

print(ne_chunk(pos_tag(word_tokenize(input))))
showing info https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/index.xml
(S
  (PERSON Edison/NNP)
  went/VBD
  to/TO
  (ORGANIZATION Tsinghua/NNP University/NNP)
  today/NN
  ./.)

数据清洗

import re
from nltk.corpus import stopwords
# 输入数据
s = '    RT @Amila #Test\nTom\'s newly listed Co  &amp; Mary\'s unlisted     Group to supply tech for nlTK.\nh $TSLA $AAPL https:// t.co/x34afsfQsh'

# 去掉html标签
s=re.sub(r'&\w*;|@\w*|#\w*','',s)

# 去掉一些价值符号
s=re.sub(r'\$\w*','',s)

# 去掉超链接
s=re.sub(r'https?:\/\/.*\/\w*','',s)

# 去掉一些专有名词 \b为单词的边界
s=re.sub(r'\b\w{1,2}\b','',s)

# 去掉多余的空格
s=re.sub(r'\s\s+','',s)

# 分词
tokens=word_tokenize(s)

# 去掉停用词
tokens=[w for w in tokens if(w not in stopwords.words('english'))]

# 最后的结果
print(' '.join(tokens))

Tom ' newly listedMary ' unlistedGroupsupply tech nlTK .

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答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,并创造出更加智能的应用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值