In [18]:
%matplotlib inline

In [91]:
import nltk
from nltk.book import *

In [3]:
text1


Out[3]:
<Text: Moby Dick by Herman Melville 1851>

In [40]:
print type(text1)
#文本的词汇个数
# print len(text1.vocab())
#搜索文本
# text1.concordance('woods')
#词语索引使我们看到词的上下文
text1.similar("monstrous")
print '\n'
text2.similar("monstrous")
print '\n'
#common_contexts允许我们研究两个或两个以上的词共同的上下文
text2.common_contexts(["monstrous", "very"])
#离散图显示特定词在文档中出现的次数
text4.dispersion_plot(["citizens", "democracy", "freedom", "duties", "America"])
print 'random words:'
#产生一些随机文 
text3.generate('save')
#text3的长度
print len(text3)
#set(text3)获得 text3 的词汇表
#对text3的词汇表进行排序
#sorted(set(text3)) 
#使用Python3的浮点数计算
from __future__ import division
#text3中每个字词平均被使用的次数
print len(text3) / len(set(text3))
# 统计稳重某一个词出现的次数
print text5.count("lol")
#统计lol出现的百分比
print 100 * text5.count('lol') / len(text5)


<class 'nltk.text.Text'>
imperial subtly impalpable pitiable curious abundant perilous
trustworthy untoward singular lamentable few determined maddens
horrible tyrannical lazy mystifying christian exasperate


very exceedingly so heartily a great good amazingly as sweet
remarkably extremely vast


a_pretty is_pretty a_lucky am_glad be_glad
random words:
44764
16.0501972033
704
1.56409686736

In [43]:
#自定义函数
def lexical_diversity(text):  #求解词的平均使用频次
    return len(text) / len(set(text))
def percentage(count, total): #求解此处先的百分比
    return 100 * count / total
print lexical_diversity(text9)
print percentage(text5.count('a'), len(text5))


10.1679153812
1.26194179071

In [50]:
#文 是什么?在一个层面上,它是一页纸上的符号序列就像这页纸一样。在另一个层面 上,它是章节的序列,
#每一章由小节序列组成,小节由段落序列组成,以此类推。然而,对 于我们而言,我们认为文 不外乎是词和标点符号的序列。
sent2


Out[50]:
['The',
 'family',
 'of',
 'Dashwood',
 'had',
 'long',
 'been',
 'settled',
 'in',
 'Sussex',
 '.']

In [48]:
lexical_diversity(sent2)


Out[48]:
1.0

In [54]:
# 链表基本操作
list01 = ['runoob', 786, 2.23, 'john', 70.2]
list02 = [123, 'john']

print list01
print list02

# 列表截取

print list01[0]
print list01[-1]
print list01[0:3]

# 列表重复

print list01 * 2

# 列表组合

print list01 + list02

# 获取列表长度

print len(list01)

# 删除列表元素

del list02[0]
print list02

# 元素是否存在于列表中

print 'john' in list02  # True

# 迭代

for i in list01:
    print i

# 比较两个列表的元素

print cmp(list01, list02)

# 列表最大/最小值

print max([0, 1, 2, 3, 4])
print min([0, 1])

# 将元组转换为列表

aTuple = (1,2,3,4)
list03 = list(aTuple)
print list03

# 在列表末尾添加新的元素

list03.append(5)
print list03

# 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)

list03.extend(list01)
print list03

# 统计某个元素在列表中出现的次数

print list03.count(1)

# 从列表中找出某个值第一个匹配项的索引位置

print list03.index('john')

# 将对象插入列表

list03.insert(0, 'hello')
print list03

# 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值

print list03.pop(0)
print list03

# 移除列表中某个值的第一个匹配项

list03.remove(1)
print list03

# 反向列表中元素

list03.reverse()
print list03

# 对原列表进行排序

list03.sort()
print list03


['runoob', 786, 2.23, 'john', 70.2]
[123, 'john']
runoob
70.2
['runoob', 786, 2.23]
['runoob', 786, 2.23, 'john', 70.2, 'runoob', 786, 2.23, 'john', 70.2]
['runoob', 786, 2.23, 'john', 70.2, 123, 'john']
5
['john']
True
runoob
786
2.23
john
70.2
1
4
0
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 'runoob', 786, 2.23, 'john', 70.2]
1
8
['hello', 1, 2, 3, 4, 5, 'runoob', 786, 2.23, 'john', 70.2]
hello
[1, 2, 3, 4, 5, 'runoob', 786, 2.23, 'john', 70.2]
[2, 3, 4, 5, 'runoob', 786, 2.23, 'john', 70.2]
[70.2, 'john', 2.23, 786, 'runoob', 5, 4, 3, 2]
[2, 2.23, 3, 4, 5, 70.2, 786, 'john', 'runoob']

In [67]:
print sent8
print len(sent8)
print sent8[13:14]
print sent8[2:5]
print ' '.join(sent8)


['25', 'SEXY', 'MALE', ',', 'seeks', 'attrac', 'older', 'single', 'lady', ',', 'for', 'discreet', 'encounters', '.']
14
['.']
['MALE', ',', 'seeks']
25 SEXY MALE , seeks attrac older single lady , for discreet encounters .

In [93]:
#1.3 简单的统计
from nltk.tokenize import word_tokenize
from nltk.probability import FreqDist
sent = 'This is an example sentence'
fdist = FreqDist()
# for word in word_tokenize(sent):
#     fdist[word.lower()] += 1
fdist = FreqDist(word.lower() for word in word_tokenize(sent))
fdist = FreqDist(text7)
#频率分布中的key,即文章的词汇
voc = fdist.keys()
print voc[:50] 
print fdist['Mortimer']
print fdist['consists']
#绘制词汇累频率图
fdist.plot(50, cumulative=True)
#细粒度的选择词
vs = set(text1)
long_words = [v for v in vs if len(v) > 15]
print long_words
print sorted(long_words)

fdist = FreqDist(text5)
long_words = [v for v in vs if len(v) > 7 and fdist[v] > 3]

print long_words
print sorted(long_words)


[u'Mortimer', u'foul', u'Heights', u'four', u'spiders', u'railing', u'centimeter', u'Until', u'payoff', u'Germany-based', u'Foundation', u'granting', u'Manufacturers', u'electricity', u'Ronald', u'153.3', u'refunding', u'Western', u'lore', u'hormone', u'Frankly', u'battles', u'45.3', u'45.2', u'regional', u'Salomon', u'appropriation', u'cavernous', u'yellow', u'Torrington', u'960', u'stabbed', u'bringing', u'Policies', u'uttering', u'scholar', u'auditor', u'Nasdaq', u'succession', u'combine', u'Paul', u'straight', u'ornamental', u'infringed', u'tired', u'Toledo', u'Off-Track', u'270', u'consists', u'second']
1
1
[u'hermaphroditical', u'subterraneousness', u'uninterpenetratingly', u'irresistibleness', u'responsibilities', u'comprehensiveness', u'uncompromisedness', u'superstitiousness', u'uncomfortableness', u'supernaturalness', u'circumnavigating', u'cannibalistically', u'circumnavigations', u'indispensableness', u'preternaturalness', u'apprehensiveness', u'CIRCUMNAVIGATION', u'simultaneousness', u'undiscriminating', u'characteristically', u'Physiognomically', u'physiognomically', u'circumnavigation', u'indiscriminately']
[u'CIRCUMNAVIGATION', u'Physiognomically', u'apprehensiveness', u'cannibalistically', u'characteristically', u'circumnavigating', u'circumnavigation', u'circumnavigations', u'comprehensiveness', u'hermaphroditical', u'indiscriminately', u'indispensableness', u'irresistibleness', u'physiognomically', u'preternaturalness', u'responsibilities', u'simultaneousness', u'subterraneousness', u'supernaturalness', u'superstitiousness', u'uncomfortableness', u'uncompromisedness', u'undiscriminating', u'uninterpenetratingly']
[u'innocent', u'somebody', u'sometimes', u'religion', u'anything', u'whispers', u'together', u'yourself', u'thinking', u'actually', u'probably', u'everybody', u'confused', u'seriously', u'daughter', u'afternoon', u'interesting', u'profiles', u'different', u'tomorrow', u'romantic', u'supposed', u'yesterday', u'listening', u'chatting', u'everything', u'happened', u'horrible', u'interested', u'questions', u'question', u'something', u'conversation', u'remember', u'watching']
[u'actually', u'afternoon', u'anything', u'chatting', u'confused', u'conversation', u'daughter', u'different', u'everybody', u'everything', u'happened', u'horrible', u'innocent', u'interested', u'interesting', u'listening', u'probably', u'profiles', u'question', u'questions', u'religion', u'remember', u'romantic', u'seriously', u'somebody', u'something', u'sometimes', u'supposed', u'thinking', u'together', u'tomorrow', u'watching', u'whispers', u'yesterday', u'yourself']
<generator object bigrams at 0x11dcc54b0>

In [96]:
#词搭配
nds = nltk.bigrams(['more', 'is', 'said', 'than', 'done'])#二元词组
for nd in nds:
    print nd
nds = nltk.trigrams(['more', 'is', 'said', 'than', 'done'])#三元词组
for nd in nds:
    print nd


('more', 'is')
('is', 'said')
('said', 'than')
('than', 'done')
('more', 'is', 'said')
('is', 'said', 'than')
('said', 'than', 'done')

In [97]:
text4.collocations()


United States; fellow citizens; four years; years ago; Federal
Government; General Government; American people; Vice President; Old
World; Almighty God; Fellow citizens; Chief Magistrate; Chief Justice;
God bless; every citizen; Indian tribes; public debt; one another;
foreign nations; political parties

In [105]:
# fdist.items()
'''
    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(c umula tive =True) 绘制累积频率分布图
    fdist1 < fdist2 测试样 在 fdist1 中出现的频率是否小于 fdist2
    
    常用字符传比较
    s.startswith(t) 测试 s 是否以 t 开头
    s.endswith(t) 测试 s 是否以 t 结尾
    t in s 测试 s 是否包  t
    s.islower() 测试 s 中所有字符是否都是小写字母
    s.isupper() 测试 s 中所有字符是否都是大写字母
    s.isalpha() 测试 s 中所有字符是否都是字母
    s.isalnum() 测试 s 中所有字符是否都是字母或数字
    s.isdigit() 测试 s 中所有字符是否都是数字
    s.istitle() 测试 s 是否首字母大写(s 中所有的词都首字母大写)
'''
fdist1 = FreqDist(text1)
# fdist2 = FreqDist(text2)
fdist1.plot(50)



In [ ]:
#1.5 自然语言理解
'''
    词意消歧
    要算出特定上下文中的词被赋予的是哪个意思
    指代消解
    要回答这个问题涉及到寻找代词 they 的先行词 thieves 或者 paintings。处理这个问题的计算技术包括
    指代消解(anaphora resolution)——确定代词或名词短语指的是什么

    语义角色标注(semantic role labeling)——确定名词短语如何与动词相关联(如施事,受 事,工具等)。
    自动生成语言
    我们将能够 继续那些包  自动生成 语言的任 务,如自动问答和机器翻译
    机器翻译
    
'''