|
| 1 | +#!/usr/bin/env python |
| 2 | +# coding: utf-8 |
| 3 | + |
| 4 | +""" |
| 5 | +Created on 2018-05-09 |
| 6 | +Updated on 2017-05-09 |
| 7 | +Author: /片刻 |
| 8 | +GitHub: https://github.com/apachecn/MachineLearning |
| 9 | +""" |
| 10 | + |
| 11 | + |
| 12 | +""" |
| 13 | +the first example for nltk book |
| 14 | +""" |
| 15 | +from nltk.book import * |
| 16 | + |
| 17 | + |
| 18 | +# 查找特定词语上下文 |
| 19 | +text1.concordance("monstrous") |
| 20 | + |
| 21 | +# 相关词查找 |
| 22 | +text1.similar("monstrous") |
| 23 | + |
| 24 | +# 查找多个词语的共同上下文 |
| 25 | +text2.common_contexts(["monstrous", "very"]) |
| 26 | + |
| 27 | +# 画出词语的离散图 |
| 28 | +text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America"]) |
| 29 | + |
| 30 | +# 产生随机文本 |
| 31 | +text3.generate() |
| 32 | +Traceback (most recent call last): |
| 33 | + File "E:/nlp/eg1.py", line 25, in <module> |
| 34 | + text3.generate() |
| 35 | +TypeError: generate() missing 1 required positional argument: 'words' |
| 36 | + |
| 37 | +# 单词数量 标识符总数 |
| 38 | +print(len(text3)) |
| 39 | + |
| 40 | +# 词汇的种类及数量 用集合set显示 |
| 41 | +print(sorted(set(text3))) |
| 42 | +print(len(set(text3))) |
| 43 | + |
| 44 | +# 测量平均每类词语被使用的次数 |
| 45 | +from __future__ import division #本命令必须放在文件的开始之初 |
| 46 | +print(len(text3)/len(set(text3))) |
| 47 | + |
| 48 | +# 统计特定单词在文本中出现的次数,并计算其占比 |
| 49 | +print(text3.count("smote")) |
| 50 | +print(100*text4.count('a')/len(text4)) |
| 51 | + |
| 52 | +# # 词的频率分布 |
| 53 | +fdist1 = FreqDist(text1) |
| 54 | +# # 输出总的词数 |
| 55 | +print(fdist1) |
| 56 | +# In Python 3 dict.keys() returns an iteratable but not indexable object. |
| 57 | +vac1 = list(fdist1.keys()) |
| 58 | +# # 输出词数最多的前五十个词 |
| 59 | +print(vac1[:50]) |
| 60 | +# # 输出whale的次数 |
| 61 | +print(fdist1["whale"]) |
| 62 | +# # 输出前五十个词的累积频率图 |
| 63 | + |
| 64 | +fdist1.plot(50) |
| 65 | + |
| 66 | +# 查找长度超过15个字符的词 |
| 67 | +V = set(text1) |
| 68 | +long_words = [w for w in V if len(w)>15] |
| 69 | +print(sorted(long_words)) |
| 70 | + |
| 71 | +# 查找长度超过7的词且频率超过7 |
| 72 | +fdist5 = FreqDist(text5) |
| 73 | +print(sorted([ w for w in set(text5) if len(w)>7 and fdist5[w]>7])) |
| 74 | + |
| 75 | +# 双连词的使用 |
| 76 | +from nltk import bigrams |
| 77 | +# # 查了一下nltk官网上的函数说明,要加list()函数,结果才是书上的情况 |
| 78 | +print(list(bigrams(['more', 'is', 'said', 'than', 'done']))) |
| 79 | + |
| 80 | +# 文本中常用的连接词 |
| 81 | +print(text4.collocations()) |
| 82 | + |
| 83 | +print([len(w) for w in text1]) |
| 84 | +fdist = FreqDist([len(w) for w in text1]) |
| 85 | +print(fdist) |
| 86 | +print(fdist.keys()) |
| 87 | +print(fdist.items()) |
| 88 | +print(fdist.max()) |
| 89 | +print(fdist[3]) |
| 90 | +print(fdist.freq(3)) |
| 91 | + |
| 92 | +print(sorted([w for w in set(text1) if w.endswith('ableness')])) |
| 93 | + |
| 94 | +print(babelize_shell()) |
0 commit comments