nltk库学习记录

nltk库主要用来处理自然语言,做段落划分、句子分割、单词分割等,可以对大型文章进行拆分解读,提取关键词。

pip install nltk--下载第三方库

句子分割,词语分割 

from nltk.tokenize import sent_tokenize,word_tokenize

nltk.download()--下载数据包,括号内不写特定数据包时,将下载全部,需要保持网络稳定,需要一定时间,有点久的。

sent_tokenize(example_text)--句子分割

word_tokenize(example_text)--词语分割

停止词 

from nltk.corpus import stopwords--stopwords 是停止词,用于判断一句话结束的词,反正我看案例好像是一些无意义的词。英语的停止词也不多,具体用来干啥也没看懂。
from nltk.tokenize import word_tokenize

example_sentence = "Today is a good day."

stop_words = set(stopwords.words("English"))--设置停止词为英语停止词

words = word_tokenize(example_sentence)--将例句按词语进行分割

filtered_sentence = []

for w in words:
    if w not in stop_words:
        filtered_sentence.append(w)

print(filtered_sentence)

还原词干,把不同词性的词语,还原成本身的词干 

from nltk.stem import PorterStemmer --还原词干
from nltk.tokenize import word_tokenize

ps = PorterStemmer()

example_words = ["python","pythoner","pythonly","pythoned","pythoning"]--不同词性,实际上意思都差不多的,所以还原成词干来处理,可以节省很多时间。

for w in example_words:
    print(ps.stem(w))--然后就会把各种词性,全部还原成python本体,不过准确率一般。

标注词性。数据量大的话,可以只提取名词,表示关键词。提取形容词,表示情绪。

import nltk
from nltk.corpus import state_union--貌似是美国各届领导人的演讲库
from nltk.tokenize import PunkSentenceTokenizer --标注词性的

train_text = state_union.raw("2005_GWBush.txt")--05年小布什的演讲

sample_text = state_union.raw("2006_GWBush.txt")

custom_sent_tokenizer = PunkSentenceTokenizer(train_text)--好像是先用训练集做出词性库

tokenized = custom_sent_tokenize(sample_text)--然后把样本集丢进去

def process_content():
    try:
        for i in tokenized:
            words = nltk.word_tokenize(i)
            tagged = nltk.pos_tag(words)--标注词性
            print(tagged)

    except Exception as e:
        print(str(e))

 结果是这样的,标注了每个单词的词性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值