习题25
python:3.9
def break_words(stuff):
这个函数会为我们分解单词
"""This function will break up words for us ."""
split()函数
语法:str.split(str="",num=string.count(str))[n]
参数说明:
str:表示为分隔符,默认为空格,但是不能为空('')。若字符串中没有分隔符,则把整个字符串作为列表的一个元素
num:表示分割次数。如果存在参数num,则仅分隔成 num+1 个子字符串,并且每一个子字符串可以赋给新的变量
[n]:表示选取第n个分片
注意:当使用空格作为分隔符时,对于中间为空的项会自动忽略
words =stuff.split(' ')
return words
def sort_words(words):
排列单词
"""Sorts the words."""
对List进行排序,sort是在原位重新排列列表,而sorted()是产生一个新的列表.
return sorted(words)
def print_first_word(words):
打印第一个弹出的单词
"""Prints the first word after popping it off."""
"""pop()指定删除对象的索引位置"""
word =words.pop(0)
print (word)
def print_last_word(words):
打印最后一个弹出的单词
"""Prints the last word after popping it off."""
"""pop()指定删除对象的索引位置"""
word = words.pop(-1)
print (word)
def sort_sentence(sentence):
接收一个完整的句子和返回到已排序的单词
"""Takes in a full sentence and returns the sorted words."""
拆解句子,化为单词
words = break_words(sentence)
返回排序单词
return sort_words(words)
def print_first_and_last(sentence):
打印句子的第一和最后一个单词
"""Prints the first and last words of the sentence."""
拆解句子,化为单词
words =break_words(sentence)
打印第一个单词
print_first_word(words)
打印最后一个单词
print_last_word(words)
def print_first_and_last_sorted(sentence):
排序单词然后打印第一个和最后一个
"""Sorts the words then prints the first and last one."""
排序句子中的单词
words=sort_sentence(sentence)
打印第一个单词
print_first_word(words)
打印最后一个单词
print_last_word(words)
这里是我自己翻译的,也有是别人那里借鉴过来的,因为我英文不好,所以我基本都翻译了一遍,如果有错误希望大家及时提醒我。下面是结果
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
>>> words
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
>>> sorted_words = ex25.sort_words(words)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_word(words)
All
>>> ex25.print_last_word(words)
wait.
>>> wrods
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'wrods' is not defined
>>> words
['good', 'things', 'come', 'to', 'those', 'who']
>>> ex25.print_first_word(sorted_words)
All
>>> ex25.print_last_word(sorted_words)
who
>>> sorted_words
['come', 'good', 'things', 'those', 'to', 'wait.']
>>> sorted_words = ex25.sort_sentence(sentence)
>>> sorted_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_and_last(sentence)
All
wait.
>>> ex25.print_first_and_last_sorted(sentence)
All
who
>>> ^Z
这个最后结束的是>>> ^Z,因为我是Windows系统
加分习题
1.研究答案中没有分析过的行,找出它们的来龙去脉。确认自己明白了自己使用的是模组ex25中定义的函数。
答同上
2.试着执行 help(ex25)和 help(ex25.break_words)。这是你得到模组帮助文档的方式。所谓帮助文档就是你定义函数时放在 “”"之间的东西,它们也被称作 documentationcomments(文档注解),后面你还会看到更多类似的东西。
这个我打不开也不知道为什么,让大家看看别的博主的吧,这是链接习题25
3.重复键入 ex25.是很烦的一件事情。有一个捷径就是用 from ex25 import *的方式导入模组。这相当于说:“我要把ex25 中所有的东西 import 进来。”程序员喜欢说这样的倒装句,开一个新的会话,看看你所有的函数是不是已经在那里了。
4 .把你脚本里的内容逐行通过 python编译器执行,看看会是什么样子。你可以执行CTRL-D(Windows 下是 CTRL-Z)来关闭编译器