Python自然语言处理练习一

1.尝试使用Python解释器作为一个计算器,输入表达式,如12/(4+1)

>>>12/(4+1)
2

2.26个字母可以组成26的10次方或者26**10个字母长的字符串,也就是141167095653376L。100个字母长度的字符串可能有多少个

>>>26**100
3142930641582938830174357788501626427282669988762475256374173175398995908420104023465432599069702289330964075081611719197835869803511992549376L

3.Python乘法运算可应用于链表。当输入['Monty','Python'] * 20或者3*sent1会发生什么?

>>>['Monty','Python'] * 20
['Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python', 'Monty', 'Python']
>>>from nltk.book import *
>>>3 * sent1
['Call', 'me', 'Ishmael', '.', 'Call', 'me', 'Ishmael', '.', 'Call', 'me', 'Ishmael', '.']

4.在text2中有多少个词?有多少个不同的词?

>>>from nltk.book import *
>>>len(text2)
141576
>>>len(set(text2))
6833

5.制作《理智与情感》中4个主角:Elinor、Marianne、Edward和Willoughby的分布图。

from nltk.book import *

text2.dispersion_plot(['Elinor','Marianne','Edward','Willoughby'])
Python自然语言处理练习一_第1张图片
nltk.png

6.查找text5中的搭配

>>> text5.collocations()
wanna chat; PART JOIN; MODE #14-19teens; JOIN PART; PART PART;cute.-ass MP3; MP3 player; JOIN JOIN; times .. .; ACTION watches; guyswanna; song lasts; last night; ACTION sits; -...)...- S.M.R.; LimePlayer; Player 12%; dont know; lez gurls; long time

7.说明python表达式用途:len(set(text4))
set()方法是获得文本的词汇表,len()方法是获取长度,该表达式的用途是获取text4文本中不同词汇的个数

8.使用text9.index()查找词sunset的索引值

>>> text9.index('sunset')
629

9.使用链表加法、set和sorted操作,计算句子sent1...sent8的词汇表

>>> sent = sent1+sent2+sent3+sent4+sent5+sent6+sent7+sent8
>>> len(set(sent))
75

10.编写一个切片表达式提取text2中的最后两个词

>>> text2[-2::]
['THE', 'END']

11.找出聊天语料库(text5)中所有4个字母的词。

[w for w in FreqDist(text5).keys() if len(w) == 4]
['left', 'with', 'this', 'name', 'PART', 'well', 'NICK', 'U121', 'golf', 'clap', 'JOIN',...]

12.使用for和if语句组合循环遍历电影剧本《巨蟒和圣杯》(text6)中的词,输出所有的大写词,每行输出一个

for w in text6:
    if w.isupper():
        print(w)

13.编写表达式并找出text6所有符合下列条件的词。
a.以ize结尾

[w for w in text6 if w.endswith('ize')]

b.包含字母z

[w for w in text6 if 'z' in w]

c.包含字母序列pt

[w for w in text6 if 'pt' in w]

d.除了首字母外全是小写字母的词

[w for w in text6 if w.istitle()]

14.定义sent为词链表['she','sells','sea','shells','by','the','sea','shore']。编写代码执行以下任务
a.输出所有sh开头的单词

>>> sent=['she','sells','sea','shells','by','the','sea','shore']
>>> [w for w in sent if w.startswith('sh')]
['she', 'shells', 'shore']

b.输出所有长度超过4个字符的词

>>> [w for w in sent if len(w) > 4]
['sells', 'shells', 'shore']

15.定义一个名为vocab_size(text)的函数,以文本作为唯一的参数,返回文本的词汇量

def vocab_size(text):
    return len(set(text))

16.定义一个函数percent(word,text),计算一个给定的词在文本中出现的频率,结果以百分比表示

def percent(word,text):
    count = 0
    for w in text:
        if word == w:
            count += 1
    return str(float(count) / float(len(text)) * 100)+'%'

你可能感兴趣的:(Python自然语言处理练习一)