首页 > 编程语言 >【笨方法学python】ex25 - 更多更多的练习

【笨方法学python】ex25 - 更多更多的练习

时间:2022-10-08 02:55:27浏览次数:60  
标签:word sentence python ex25 words print last first 方法学

代码如下:

点击查看代码
# coding=utf-8
# 更多更多的练习

def break_words(stuff):  # 定义 stuff 函数
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words


# Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分割成 (num+1) 个子字符串。


def sort_words(words):
    """Sorts the words."""
    return sorted(words)  # 对序列(列表、元组、字典、集合、还包括字符串)进行排序。


def print_first_word(words):
    """Prints the first word after popping it off."""
    word = words.pop(0)  # pop(0) :删除第一个元素
    print word


def print_last_word(words):
    """Prints the last word after popping it off."""
    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)


def filename_get():  # 获取文件名
    name = "ex25"
    return name


target = open(filename_get())  # 打开文件
txt = target.read()

# 以下为调用各方法内容

# print target.read()
print "-------break_words------------"
# break_words = break_words(txt)
# print break_words
# # 调用 break_words
print "-------sort_words-------------"
# sort_words = sort_words(txt)
# print sort_words
# print sort_words(target.read())
print "-------print_first_word-------"
# list1 = ['First', 'Second', 'Third']
# print_first_word(list1)
# print list1
print "-------print_last_word--------"
# list1 = ['First', 'Second', 'Third']
# print_last_word(list1)
# print list1
print "-------sort_sentence----------"
# sort_sentence = sort_sentence(txt)
# print break_words(txt)
# print sort_sentence  # 排序
print "-------print_first_and_last---"
# print print_first_and_last(txt)
print "-------print_first_and_last)sorted"
# print print_first_and_last_sorted(txt)

其中,ex25文件内容为:

点击查看代码
A Blooming Tree
May Buddha let us meet
in my most beautiful hours,
I have prayed for it
for five hundred years
Buddha made me a tree
by the path you may take,
In full blossoms
Im waiting in the sun
every flower carrying my previous hope
As you are near, listen carefully
the quivering leaves are my waiting zeal,
As you pass by the tree
without noticing me,My friend, upon the ground behind you
is not the fallen petals but my withered heart

执行结果各不相同,需依次删除 “#” 测试。

标签:word,sentence,python,ex25,words,print,last,first,方法学
From: https://www.cnblogs.com/TiramisuPS/p/16767800.html

相关文章