nltk

ntlk是一个比较常用的用于自然语言处理的python库,在这篇文章中,将会对ntlk的使用进行总结和归纳。

相关代码示例

text = ’Don’t hesitate to ask questions. Be positive‘

  1. 安装:安装使用pip正常安装即可,但是在第一次使用前要利用download命令,并在弹出的下载器中下载相应的文件包,全部下载需要2G左右。下载时要开VPN,否则服务器会没有响应。如果下载还是不成功,可以尝试从github/nltk中下载需要的package并放在默认路径中(APPDATA)

    1
    2
    import nltk
    nltk.download()
  1. 测试安装是否成功:导出包中的预置文本从而判断包有没有下载成功

    1
    2
    3
    4
    5
    6
    from nltk.corpus import brown
    print(brown.words())
    print(len(brown.sents())) # 句子数
    print(len(brown.words())) # 单词数

    from nltk.book import *
  1. 文本切分成语句:对text进行语句划分,输出为sentence的list

    1
    2
    3
    4
    5
    6
    7
    8
    # 方法一
    from nltk.tokenize import sent_tokenize
    print(sent_tokenize(text))
    # Out: ["Don't hesitate to ask questions.", 'Be positive.']

    # 方法二
    tokenizer=nltk.data.load('tokenizers/punkt/english.pickle') print(tokenizer.tokenize(text))
    # Out: ["Don't hesitate to ask questions.", 'Be positive.']
  1. 语句分词:对sentence进行划分,最终得到words

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    # 方法一:TreebankWordTokenizer依据Penn Treebank语料库约定,通过分离缩略词来实现划分
    words=nltk.word_tokenize(text)
    print(words)
    # Out: ['Do', "n't", 'hesitate', 'to', 'ask', 'questions', '.', 'Be', 'positive', '.']

    #方法二:PunctWordTokenizer通过分离标点实现划分,每一个单词都会被保留
    from nltk.tokenize import WordPunctTokenizer tokenizer=WordPunctTokenizer() words = tokenizer.tokenize(text) print(words
    # Out: ['Don', "'", 't', 'hesitate', 'to', 'ask', 'questions', '.', 'Be', 'positive', '.']

    # 其他分词方法
    # RegexpTokenizer、WhitespaceTokenizer、BlanklineTokenizer
  1. 概率分布:nltk.probability.FreqDist

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    fdist = FreqDist(samples)        # 创建包含给定样本的频率分布,参数为词的列表 
    fdist.inc(sample) # 增加样本
    fdist['monstrous'] # 计数给定样本出现的次数
    fdist.freq('monstrous') # 给定样本的频率
    fdist.N() # 样本总数
    fdist.keys() # 以频率递减顺序排序的样本链表
    for sample in fdist: # 以频率递减的顺序遍历样本
    fdist.max() # 数值最大的样本
    fdist.tabulate() # 绘制频率分布表
    fdist.plot() # 绘制频率分布图
    fdist.plot(cumulative=True) # 绘制累积频率分布图
    fdist1 < fdist2 # 测试样本在 fdist1 中出现的频率是否小于 fdist2
  1. 条件概率分布:nltk.probability.ConditionalFreqDist

    1
    2
    3
    4
    5
    6
    7
    8
    9
    cfdist= ConditionalFreqDist(pairs)      # 从配对链表中创建条件频率分布 
    cfdist.conditions() # 将条件按字母排序
    cfdist[condition] # 此条件下的频率分布
    cfdist[condition][sample] # 此条件下给定样本的频率
    cfdist.tabulate() # 为条件频率分布制表
    cfdist.tabulate(samples, conditions) # 指定样本和条件限制下制表
    cfdist.plot() # 为条件频率分布绘图
    cfdist.plot(samples, conditions) # 指定样本和条件限制下绘图
    cfdist1 < cfdist2 # 测试样本在 cfdist1 中出现次数是否小于在 cfdist2 中出现次数
  1. 文本整体统计分析:nltk.text.Text()类用于对文本进行初级的统计与分析

    1
    2
    3
    4
    5
    6
    7
    8
    Text(words)                             # 对象构造,参数为词的列表 
    concordance(word, width, lines) # 显示 word 出现的上下文
    common_contexts(words) # 显示words出现的相同模式
    similar(word) # 显示 word 的相似词
    collocations(num, window_size) # 显示最常见的二词搭配
    count(word) # word 出现的词数
    dispersion_plot(words) # 绘制 words 中文档中出现的位置图
    vocab() # 返回文章去重的词典
  1. 语料库:nltk.corpus

    1
    2
    3
    4
    5
    6
    gutenberg   # 大约有 36000 本免费电子图书,多是古典作品 
    webtext # 网络小说、论坛、网络广告等内容
    nps_chat # 有上万条聊天消息语料库,即时聊天消息为主
    brown # 一个百万词级别的英语电子语料库,这个语料库包含 500 个不同来源的文本,按 文体分类有新闻、社论等
    reuters # 路透社语料库,上万篇新闻方档,约有 1 百万字,分 90 个主题,并分为训练集和 测试集两组
    inaugural # 演讲语料库,几十个文本,都是总统演说
  1. 语料库操作

    1
    2
    3
    4
    5
    6
    7
    8
    fileids()                             # 返回语料库中文件名列表 
    fileids[categories] # 返回指定类别的文件名列表
    raw(fid=[c1,c2]) # 返回指定文件名的文本字符串
    raw(catergories=[]) # 返回指定分类的原始文本
    sents(fid=[c1,c2]) # 返回指定文件名的语句列表
    sents(catergories=[c1,c2]) # 按分类返回语句列表
    words(filename) # 返回指定文件名的单词列表
    words(catogories=[]) # 返回指定分类的单词列表
  1. 提取词干:取出单词中的词缀,得到单词的词根或者词干,搜索引擎大多会使用词干提取来获取词干并将其存储作为索引词

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    # 方法一:在 NLTK 中使用 PorterStemmer 类进行词干
    import nltk from nltk.stem
    import PorterStemmer
    stemmerporter = PorterStemmer()
    stemmerporter.stem('happiness')
    # Out: 'happi'

    # 方法二2:LancasterStemmer 类在 NLTK 中用于实现 Lancaster 词干提取算法
    import nltk from nltk.stem
    import LancasterStemmer
    stemmerlan=LancasterStemmer()
    stemmerlan.stem('happiness')
    Out: 'happy'

    # 方法三
    # 过使用 RegexpStemmer 类构建词干提取器,通过接受一个字符串,并在找到其匹配的单词使删除该单词的前缀和后缀
  1. 词性标注:对单词的词性如名词,动词形容词等属性进行标记,nltk.tag包中包含词性标注器,被TaggerIbase继承

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    # 英文标注通常使用nltk,对中文标注时常使用jieba模块
    import nltk
    text1=nltk.word_tokenize("It is a pleasant day today") nltk.pos_tag(text1)
    # Out: [('It', 'PRP'), ('is', 'VBZ'), ('a', 'DT'), ('pleasant', 'JJ'), ('day', 'NN'), ('today', 'NN')]

    # jieba标注中文文本
    seg = jieba.posseg.cut(sentence_words)
    l = []
    for j in seg:
    l.append(j.word)
    l.append(j.flag)
    print(l, file=output)
  1. 清除标点符号:中英文均可

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    def filter_punctuation(words): 
    new_words = [];
    illegal_char = string.punctuation + '【·!…()—:“”?《》、;】'
    pattern=re.compile('[%s]' % re.escape(illegal_char))
    for word in words:
    new_word = pattern.sub(u'', word)
    if not new_word == u'':
    new_words.append(new_word)
    return new_words
    words_no_punc = filter_punctuation(words)
    print(words_no_punc)
    # Out: ['Don', 't', 'hesitate', 'to', 'ask', 'questions', 'Be', 'positive']
  1. 大小写转换

    1
    2
    3
    4
    print(text.lower()) 
    print(text.upper())
    # Out: don't hesitate to ask questions. be positive.
    # DON'T HESITATE TO ASK QUESTIONS. BE POSITIVE.
  1. 处理停止词
1
2
3
4
from nltk.corpus import stopwords 
stops=set(stopwords.words('english'))
words = [word for word in words if word.lower() not in stops]
print(words)
0%