python自然语言处理 第一章习题

 

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

>>> 12/(4+1)
2.4

2. 26 个字母可以组成 26 的 10 次方或者 26**10个 10 字母长的字符串。 也就是 141167095653376L(结尾处的 L 只是表示这是 Python 长数字格式)。100 个字母长度的字符串可能有多少个?

>>> 26**100
3142930641582938830174357788501626427282669988762475256374173175398995908420104023465432599069702289330964075081611719197835869803511992549376

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']
>>> 3*sent1
['Call', 'me', 'Ishmael', '.', 'Call', 'me', 'Ishmael', '.', 'Call', 'me', 'Ishmael', '.']

 

4.复习1.1节关于语言计算的内容。在text2中有多少个词?有多少个不同的词?

>>> len(text2)
141576
>>> len(set(text2))
6833

5.比较表格1-1中幽默和言情小说的词汇多样性得分,哪一个文体中词汇更丰富?

在表1-1中,言情小说的词汇多样性得分更高,所以词汇更丰富

6.制作《理智与情感》中四个主角:Elinor、Marianne、Edward 和 Willoughby 的分布图。在这部小说中关于男性和女性所扮演的不同角色,你能观察到什么?你能找出一对夫妻吗?

>>> text2.dispersion_plot(['Elinor','Edward','Willoughby','Marianne'])

python自然语言处理 第一章习题_第1张图片

 

7.查找text5中的搭配

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

8.思考下面的Python表达式:len(set(text4))。说明这个表达式的用途,并且描述在执行此计算中设计的两个步骤。

得到text4中不重复词汇及标点的数量
1.使用set对text4去重
2.使用len的到不重复词汇数量

9.复习1-2节关于链表和字符串的内容。

a定义一个字符串,并且将它分配给一个变量,如:my_string = 'My String' (在字符串中放一些更有趣的东西)。用两种方法输出这个变量的内容,一种是通过简单地输入变量的名称,然后按回车;另一种是通过使用print语句。

>>> my_string = 'Is this a watermelon?'
>>> my_string
'Is this a watermelon?'
>>> print(my_string)
Is this a watermelon?

b.尝试使用 my_string + my_string 或者用它乘以一个数将字符串添加到它自身,例如: my_string*3。请注意,连接在一起的字符串之间没有空格。怎样才能解决这个问题?

>>> my_string = (my_string + ' ') * 3
>>> print(my_string)
Is this a watermelon? Is this a watermelon? Is this a watermelon? 

10. 使用语法 my_sent = ["My", "sent"],定义一个词链表变量 my_sent(用自己喜欢的词或喜欢的话)。

a.使用''.join(my_sent)将其转换成一个字符串。

my_sent = ['My','sent']
my_sent = ' '.join(my_sent)

b.使用split()在你指定的地方将字符串分割回链表。

my_sent = my_sent.split()
print(my_sent)

输出:

['My', 'sent']

11.定义几个包含词链表的变量,例如:phrase1、phrase2 等。将它们连接在一起组成不同的组合(使用加法运算符),最终形成完整的句子。len(phrase1 + phrase2) 与 len(phrase1) + len(phrase2)之间的关系是什么?

phrase1 = ['hello','thank','you']
phrase2 = ['you','are','welcome']
print(phrase1 + phrase2)
print(len(phrase1+phrase2))
print(len(phrase1)+len(phrase2))
['hello', 'thank', 'you', 'you', 'are', 'welcome']
6
6

所以关系为相等

12. 考虑下面两个具有相同值的表达式。哪一个在NLP中更常用?为什么?
a."Monty Python"[6:12]

b.["Monty", "Python"][1]

第二种更常用,因为NLP是基于词汇的

13. 我们已经学习啦如何用词链表表示一个句子,其中每个词是一个字符序列。sent1[2][2]代表什么意思?为什么?并尝试其他的索引值。

>>> sent1[2][2]
'h'
代表sent1的第三个词汇的第三个字母

14. 在变量sent3中保存的是text3的第一句话。在sent3中the的索引值是1,因为sent3[1]的值是“the”。sent3中“the”的其他两种出现的索引值是多少?

>>> [i for i,w in enumerate(sent3) if w == 'the']
[1, 5, 8]

15. 复习1.4节讨论的条件语句。在聊天语料库(text5)中查找所有以字母b开头的词。按字母顺序显示出来。

print(sorted([w for w in set(text5) if w.startswith('b')]))

16. 在Python解释器提示符下输入表达式range(10)。再尝试range(10, 20),range(10, 20, 2)和range(10, 20, -2)。在后续章节中我们将看到遮盖内置函数的多种用途。

>>> range(10)
range(0, 10)
>>> range(10,20)
range(10, 20)
>>> range(10, 20, 2)
range(10, 20, 2)
>>> range(10, 20, -2)

17. 使用text9.index()查找词sunset的索引值。你需要将这个词作为一个参数插入到圆括号之间。在尝试和出错的过程中,在完整的句子中找到包含这个词的切片。

 Use text9.index() to find the index of the word sunset. You’ll need to insert this word as an argument between the parentheses. By a process of trial and error, find the slice for the complete sentence that contains this word. 通过反复试验,找出包含这个单词的完整句子的切分。

解题思路:设置两个链表,一个用来存储'sunset'索引值,一个存储句子结束标点的索引值。
def solution(keyword, text):
    pun = [i for i, j in enumerate(text) if j == '.' or j == '?' or j == '!']
    sunset = [i for i, j in enumerate(text) if j == keyword]
    ans = []
    flag = 0
    for i in range(len(sunset)):
        j = flag
        while j < len(pun):
            if sunset[i] < pun[j] and pun[j - 1] < sunset[i]:
                ans.append([pun[j - 1] + 1, pun[j] + 1])
                flag = j + 1
                break
            j += 1
    # print ans
    for i in range(len(ans)):
        print ('start from %d to end in %d' % (ans[i][0], ans[i][1]))
        print (' '.join(text[ans[i][0]: ans[i][1]]))

solution('sunset',text9)

运行结果:

start from 613 to end in 644
CHAPTER I THE TWO POETS OF SAFFRON PARK THE suburb of Saffron Park lay on the sunset side of London , as red and ragged as a cloud of sunset .
start from 1411 to end in 1434
This particular evening , if it is remembered for nothing else , will be remembered in that place for its strange sunset .
start from 1628 to end in 1657
For a long time the red - haired revolutionary had reigned without a rival ; it was upon the night of the sunset that his solitude suddenly ended .
start from 13325 to end in 13337
He walked on the Embankment once under a dark red sunset .
start from 13352 to end in 13385
The sky , indeed , was so swarthy , and the light on the river relatively so lurid , that the water almost seemed of fiercer flame than the sunset it mirrored .
start from 16304 to end in 16329
Every trace of the passionate plumage of the cloudy sunset had been swept away , and a naked moon stood in a naked sky .
start from 27010 to end in 27022
The sealed and sullen sunset behind the dark dome of St .
start from 49311 to end in 49342
Nevertheless , the ride had been a long one , and by the time they reached the real town the west was warming with the colour and quality of sunset .
start from 52086 to end in 52109
Up this side street the last sunset light shone as sharp and narrow as the shaft of artificial light at the theatre .
start from 60786 to end in 60865
His silk hat was broken over his nose by a swinging bough , his coat - tails were torn to the shoulder by arresting thorns , the clay of England was splashed up to his collar ; but he still carried his yellow beard forward with a silent and furious determination , and his eyes were still fixed on that floating ball of gas , which in the full flush of sunset seemed coloured like a sunset cloud .
start from 64698 to end in 64738
Then his carriage took a turn of the path , and he saw suddenly and quietly , like a long , low , sunset cloud , a long , low house , mellow in the mild light of sunset .

 

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

 

print(sorted(set(sent1 + sent8 + sent6 + sent6 + sent5 + sent4 + sent3 + sent2)))
输出:
['!', ',', '-', '.', '1', '25', ':', 'ARTHUR', 'Call', 'Citizens', 'Dashwood', 'Fellow', 'God', 'House', 'I', 'In', 'Ishmael', 'JOIN', 'KING', 'MALE', 'PMing', 'Representatives', 'SCENE', 'SEXY', 'Senate', 'Sussex', 'The', 'Whoa', '[', ']', 'a', 'and', 'attrac', 'been', 'beginning', 'clop', 'created', 'discreet', 'earth', 'encounters', 'family', 'for', 'had', 'have', 'heaven', 'in', 'lady', 'lol', 'long', 'me', 'of', 'older', 'people', 'problem', 'seeks', 'settled', 'single', 'the', 'there', 'to', 'wind', 'with']

19. 下面两行之间的差异是什么?哪一个的值比较大?其他文本也是同样情况吗?

a. sorted(set([w.lower() for w in text1]))

b. sorted([w.lower() for w in set(text1)])

存在只有大小写不同的单词时a.比b.小,其他时候长度相同。

20. w.isupper()和 not w.islower()这两个测试之间的差异是什么

w.isupper() 字母全部大写是返回True
not w.islower() 存在大写字母返回True

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

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

22. 找出聊天语聊库(text5)中所有4个字母的词。使用频率分布函数(FreqDist),以频率从高到低显示这些词。

text5_fq = nltk.FreqDist(w for w in text5 if len(w) == 4)
print(sorted(text5_fq,key=lambda x:text5_fq[x],reverse=True))

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

print([w for w in text6 if w.isupper()])

24. 编写表达式并找出text6中所有符合下列条件的词。结果应该以词链表形式表示:['word1', 'word2'...]。

a.以ize结尾。

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

b.包含字母z。

print([w for w in text6 if 'z' in w])

c.包含字母序列pt。

print([w for w in text6 if 'pt' in w])

d.除了首字母外是全部小写字母的词(即titlecase)。

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

25. 定义sent为词链表['she', 'sells', 'sea', 'shells', 'by', 'the', 'sea', 'shore']。编写代码执行以下任务。

a.输出所有sh开头的单词。

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

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

print([w for w in sent if len(w) > 4])

26. 下面的Python代码是做什么的?sum([len(w) for w in text1]),你可以用它来算出一个文本的平均字长吗?

作用:计算text1中所有单词长度的和
>>> sum([len(w) for w in text1]) / len(text1) #计算平均字长

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

def vocab_size(text):
    return len(set([w.lower() for w in text if w.isalpha()]))
print(vocab_size(text1))
输出:
16948

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

def percent(word,text):
    print("%s" % (nltk.FreqDist(text).freq(word)*100) ,"%")
    return
percent('the',brown.sents(categories='news')[1])
输出:
13.953488372093023 %

29.我们一直在使用集合存储词汇表。试试下面的Python表达式:set(sent3) < set(text1)。尝试在set()中使用不同的参数。它是做什么用的?您呢个想到一个实际的应用吗?

作用:sent3的每个元素是否被包含在在text1中

你可能感兴趣的:(python自然语言处理 第一章习题)