python自然语言处理答案_《用Python进行自然语言处理》 第一章练习题答案

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

>>> 12 / (4 + 1)

2.4

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

>>> 26 ** 100

31429306415829388301743577885016264272826699887624752563741731753989959084

201040234654325990697022893309640750816117197835869803511992549376

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']

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

>>> len(text2)

141576

>>> len(set(text2))

6833

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

言情小说

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

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

Elinor和Edward是夫妻,原因不明。。。

题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; guys

wanna; song lasts; last night; ACTION sits; -...)...- S.M.R.; Lime

Player; Player 12%; dont know; lez gurls; long time

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

1.text4中不重复单词的数量。

2.步骤一:将text4中的所有单词加入set中去重

步骤二:求该set的大小

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

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

>>> my_string = 'Hello NLP'

>>> my_string

'Hello NLP'

>>> print(my_string)

Hello NLP

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

>>> my_string * 3

'Hello NLPHello NLPHello NLP'

>>> (my_string + ' ') * 3

'Hello NLP Hello NLP Hello NLP '

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

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

>>> my_sent = ['July', 'Treee']

>>> ' '.join(my_sent)

'July Treee'

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

>>> 'July Treee'.split(' ')

['July', 'Treee']

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

>>> phrase1 = ['Good', 'morning']

>>> phrase2 = ['July', 'Treee']

>>> phrase1 + phrase2

['Good', 'morning', 'July', 'Treee']

>>> len(phrase1 + phrase2)

4>>> sorted(set(sent1 + sent2 + sent3 + sent4 + sent5 + sent6 + sent7 + sent8))

['!', ',', '-', '.', '1', '25', '29', '61', ':', 'ARTHUR', 'Call', 'Citizens', 'Dashwood', 'Fellow', 'God', 'House', 'I', 'In', 'Ishmael', 'JOIN', 'KING', 'MALE', 'Nov.', 'PMing', 'Pierre', 'Representatives', 'SCENE', 'SEXY', 'Senate', 'Sussex', 'The', 'Vinken', 'Whoa', '[', ']', 'a', 'and', 'as', 'attrac', 'been', 'beginning', 'board', 'clop', 'created', 'director', 'discreet', 'earth', 'encounters', 'family', 'for', 'had', 'have', 'heaven', 'in', 'join', 'lady', 'lol', 'long', 'me', 'nonexecutive', 'of', 'old', 'older', 'people', 'problem', 'seeks', 'settled', 'single', 'the', 'there', 'to', 'will', 'wind', 'with', 'years']

>>> len(phrase1) + len(phrase2)

4

# len(phrase1 + phrase2) equals to len(phrase1) + len(phrase2)

考虑下面两个具有相同值的表达式。哪一个在NLP中更常用?为什么?

“Monty Python”[6:12]

[“Monty”, “Python”][1]

第二种,因为NLP的操作是基于词汇的。

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

sent1中的第三个单词的第三个字母。

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

>>> for i in range(len(sent3)):

... if sent3[i] == 'the':

... print(i)

...

1

5

8

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

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

['b', 'b-day', 'b/c', 'b4', 'babay', 'babble', 'babblein', 'babe', 'babes', 'babi', 'babies', 'babiess', 'baby', 'babycakeses', 'bachelorette', 'back', 'backatchya', 'backfrontsidewaysandallaroundtheworld', 'backroom', 'backup', 'bacl', 'bad', 'bag', 'bagel', 'bagels', 'bahahahaa', 'bak', 'baked', 'balad', 'balance', 'balck', 'ball', 'ballin', 'balls', 'ban', 'band', 'bandito', 'bandsaw', 'banjoes', 'banned', 'baord', 'bar', 'barbie', 'bare', 'barely', 'bares', 'barfights', 'barks', 'barn', 'barrel', 'base', 'bases', 'basically', 'basket', 'battery', 'bay', 'bbbbbyyyyyyyeeeeeeeee', 'bbiam', 'bbl', 'bbs', 'bc', 'be', 'beach', 'beachhhh', 'beam', 'beams', 'beanbag', 'beans', 'bear', 'bears', 'beat', 'beaten', 'beatles', 'beats', 'beattles', 'beautiful', 'because', 'beckley', 'become', 'bed', 'bedford', 'bedroom', 'beeeeehave', 'beeehave', 'been', 'beer', 'before', 'beg', 'begin', 'behave', 'behind', 'bein', 'being', 'beleive', 'believe', 'belive', 'bell', 'belly', 'belong', 'belongings', 'ben', 'bend', 'benz', 'bes', 'beside', 'besides', 'best', 'bet', 'betrayal', 'betta', 'better', 'between', 'beuty', 'bf', 'bi', 'biatch', 'bible', 'biebsa', 'bied', 'big', 'bigest', 'biggest', 'biiiatch', 'bike', 'bikes', 'bikini', 'bio', 'bird', 'birfday', 'birthday', 'bisexual', 'bishes', 'bit', 'bitch', 'bitches', 'bitdh', 'bite', 'bites', 'biyatch', 'biz', 'bj', 'black', 'blade', 'blah', 'blank', 'blankie', 'blazed', 'bleach', 'blech', 'bless', 'blessings', 'blew', 'blind', 'blinks', 'bliss', 'blocking', 'bloe', 'blood', 'blooded', 'bloody', 'blow', 'blowing', 'blowjob', 'blowup', 'blue', 'blueberry', 'bluer', 'blues', 'blunt', 'board', 'bob', 'bodies', 'body', 'boed', 'boght', 'boi', 'boing', 'boinked', 'bois', 'bomb', 'bone', 'boned', 'bones', 'bong', 'boning', 'bonus', 'boo', 'booboo', 'boobs', 'book', 'boom', 'boooooooooooglyyyyyy', 'boost', 'boot', 'bootay', 'booted', 'boots', 'booty', 'border', 'borderline', 'bored', 'boredom', 'boring', 'born', 'born-again', 'bosom', 'boss', 'bossy', 'bot', 'both', 'bother', 'bothering', 'bottle', 'bought', 'bounced', 'bouncer', 'bouncers', 'bound', 'bout', 'bouts', 'bow', 'bowl', 'box', 'boy', 'boyfriend', 'boys', 'bra', 'brad', 'brady', 'brain', 'brakes', 'brass', 'brat', 'brb', 'brbbb', 'bread', 'break', 'breaks', 'breath', 'breathe', 'bred', 'breeding', 'bright', 'brightened', 'bring', 'brings', 'bro', 'broke', 'brooklyn', 'brother', 'brothers', 'brought', 'brown', 'brrrrrrr', 'bruises', 'brunswick', 'brwn', 'btw', 'bucks', 'buddyyyyyy', 'buff', 'buffalo', 'bug', 'bugs', 'buh', 'build', 'builds', 'built', 'bull', 'bulls', 'bum', 'bumber', 'bummer', 'bumped', 'bumper', 'bunch', 'bunny', 'burger', 'burito', 'burned', 'burns', 'burp', 'burpin', 'burps', 'burried', 'burryed', 'bus', 'buses', 'bust', 'busted', 'busy', 'but', 'butt', 'butter', 'butterscotch', 'button', 'buttons', 'buy', 'buying', 'bwahahahahahahahahahaha', 'by', 'byb', 'bye', 'byeee', 'byeeee', 'byeeeeeeee', 'byeeeeeeeeeeeee', 'byes']

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

>>> for i in range(10, 20, 2):

... print(i)

...

10

12

14

16

18

>>> for i in range(20, 10, -2):

... print(i)

...

20

18

16

14

12

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

>>> text9.index('sunset')

629

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

>>> sorted(set(sent1 + sent2 + sent3 + sent4 + sent5 + sent6 + sent7 + sent8))

['!', ',', '-', '.', '1', '25', '29', '61', ':', 'ARTHUR', 'Call', 'Citizens', 'Dashwood', 'Fellow', 'God', 'House', 'I', 'In', 'Ishmael', 'JOIN', 'KING', 'MALE', 'Nov.', 'PMing', 'Pierre', 'Representatives', 'SCENE', 'SEXY', 'Senate', 'Sussex', 'The', 'Vinken', 'Whoa', '[', ']', 'a', 'and', 'as', 'attrac', 'been', 'beginning', 'board', 'clop', 'created', 'director', 'discreet', 'earth', 'encounters', 'family', 'for', 'had', 'have', 'heaven', 'in', 'join', 'lady', 'lol', 'long', 'me', 'nonexecutive', 'of', 'old', 'older', 'people', 'problem', 'seeks', 'settled', 'single', 'the', 'there', 'to', 'will', 'wind', 'with', 'years']

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

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

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

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

17231

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

19317

# 第二个更大,第二个的值应大于等于第一个的值,因为在第二个中大小写不同的单词都会被保存下来。

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

w.isupper()返回的是w是否为全大写的字母

not w.islower()返回的是w是否全不是小写字母(可能包含数字等)

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

>>> text2[-2:]

['THE', 'END']

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

>>> FreqDist([w for w in text5 if len(w) == 4])

FreqDist({'JOIN': 1021, 'PART': 1016, 'that': 274, 'what': 183, 'here': 181, '....': 170, 'have': 164, 'like': 156, 'with': 152, 'chat': 142, ...})

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

>>> for w in text6:

... if w.isupper():

... print(w)

...

SCENE

KING

ARTHUR

SOLDIER

ARTHUR

...

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

以ize结尾。

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

[]

包含字母z。

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

['zone', 'amazes', 'Fetchez', 'Fetchez', 'zoop', 'zoo', 'zhiv', 'frozen', 'zoosh']

包含字母序列pt。

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

['empty', 'aptly', 'Thpppppt', 'Thppt', 'Thppt', 'empty', 'Thppppt', 'temptress', 'temptation', 'ptoo', 'Chapter', 'excepting', 'Thpppt']

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

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

['Whoa', 'Halt', 'Who', 'It', 'I', 'Arthur', 'Uther', 'Pendragon', 'Camelot', 'King', 'Britons', 'Saxons', 'England', 'Pull', 'I', 'Patsy', 'We', 'Camelot', 'I', 'What', 'Ridden', 'Yes'...

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

输出所有sh开头的单词。

>>> [w for w in sent if w.startswith('sh')]

['she', 'shells', 'shore']

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

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

['sells', 'shells', 'shore']

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

# 计算text1文本中所有单词的总长度

>>> sum([len(w) for w in text1]) / len(text1)

3.830411128023649

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

>>> def vocab_size(text):

... return len(text)

...

>>> vocab_size(text1)

260819

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

>>> def percent(word, text):

... lst_len = len([w for w in text if w == word])

... return '%.2f%%' % (lst_len / len(text))

...

>>> percent('the', text1)

'0.05%'

>>> percent('and', text1)

'0.02%'

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

>>> set(sent3) < set(text1)

True

# sent3中的每一个元素是否都在text1中

# 可用于判断一个集合是否为另一个集合的子集

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值