第3章 加工原料文本

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baiziyuandyufei/article/details/52254688

爬虫相关的题目,我会写在以后的Python爬虫部分,敬请期待。
1、定义一个字符串s=’colorless’。写一个Python语句将其变为’colourless’,只使用切片和连接操作。

>>> s = 'colorless'
>>> s = s[:4]+'u'+s[4:]
>>> s
'colourless'

2、我们可以使用切片符号删除词汇形态上的结尾。例如’dogs’[:-1]删除了dogs的最后一个字符,留下dog。使用切片符号删除下面这些词的词缀(我们插入了一个连字符指示词缀的边界,请在你的字符串中省略掉连字符):dish-es,run-ning,nation-ality,un-do,pre-heat。

>>> 'dishes'[:-2]
'dish'
>>> 'running'[:-4]
'run'
>>> 'nationality'[:-5]
'nation'
>>> 'undo'[:-2]
'un'
>>> 'preheat'[:-4]
'pre'

3、我们看到如何产生一个IndexError,通过索引超出了一个字符串的末尾。构造一个向左走的太远走到字符串的前面的索引,这有可能吗?

>>> 'abc'[:-10]
''
>>> 'abc'[-10:]
'abc'
>>> 

4、我们可以分片指定一个“步长”。下面的表达式间隔一个字符返回一个片内字符:monty[6:11:2]。也可以反向进行:monty[10:5:-2]。自己尝试一下,然后实验不同的步长。

>>> sent4
['Fellow', '-', 'Citizens', 'of', 'the', 'Senate', 'and', 'of', 'the', 'House', 'of', 'Representatives', ':']
>>> sent4[6:11:2]
['and', 'the', 'of']
>>> sent4[10:5:-2]
['of', 'the', 'and']
>>> 

5、如果你让解释器处理monty[::-1]会发生什么?解释为什么这是一个合理的结果

>>> sent4
['Fellow', '-', 'Citizens', 'of', 'the', 'Senate', 'and', 'of', 'the', 'House', 'of', 'Representatives', ':']
>>> sent4[::-1]
[':', 'Representatives', 'of', 'House', 'the', 'of', 'and', 'Senate', 'the', 'of', 'Citizens', '-', 'Fellow']

6、说明以下的正则表达式匹配的字符串类:
a. [a-zA-Z]+ # 所有英文字符
b. [A-Z][a-z]* # 首字母大写的单词串
c. p[aeiou]{,2}t # p开始,t结尾,中间为最多两个原因组成的单词
d. \d+(.\d++)? # 一个或多个数字+.一个或多个数字
e. ([^aeiou][aeiou][^aeiou])* # 辅音字母开始,一个元音字母,一个辅音字母
f. \w+|^\w\s] # 一个或多个字母+非字母非空白符

猜你喜欢

转载自blog.csdn.net/baiziyuandyufei/article/details/52254688