Python.第六章函数应用实例

# 函数应用实例

# 例6-16
# 编写函数,接收任意多的参数,返回一个元组
# 其中第一个元素为所有参数的平均值,其他元素为所有参数中大于平均值的实数

def favg(*a):


    b = sum(a) / len(a)
    c = [i for i in a if i > b]

    return (b,c)

m,n = favg(6.7, 2.4, -0.1, 2.15, -5.8)

print('平均值:',m)
print('大于平均值的数:',n)

# 平均值: 1.07
# 大于平均值的数: [6.7, 2.4, 2.15]



# 例6-17
# 编写函数,提取短语的首字母缩略词,缩略词是由短语中每一个单词取首字母组合而成的,且要求大写
# 例如,“very important person”的缩略词是“VIP”

# def Fu(s):

#     lst = s.split()
#     # print(lst)
#     c = [i[0].upper() for i in lst]
#     return c   # ['V', 'I', 'P']

# s = input('输入短语:')
# # 输入短语:very import people

# print(''.join(Fu(s)))    # 用join连接
# # VIP



# 例6-18
# 小明做打字测试,请编写程序计算小明输入字符串的准确率
# [分析] 假设原始字符串为 origin,小明输入的字符串为 userInput
# 如果两个字符申的长度不一致,提示小明重新输入
# 如果长度一致,进行字符匹配,准确率为正确的字符个数除以字符总个数

# def f(origin,yourself):
#     c = 0
#     for origin_char,yourself_char in zip(origin,yourself):
#         if origin_char == yourself_char:
#             c = c + 1
#     rate = c / len(origin)
#     return rate
#
#
# origin = 'Your smile will make my whole world bright.'
# print(origin)
# yourself = input("请输入:")
#
# if len(origin) != len(yourself):
#     print('字符长度不一致,请重新输入')
# else:
#     print('准确率为:{:.2%}'.format(f(origin,yourself)))

# 请输入:Your smile will make my whole world bright.
# 准确率为:100.00%


#  zip 函数的作用是将对应元素打包成一个个元组,然后返回由这些元组组成的对象
# ('Y','Y'), ('o','o'), ('u','u'), ('r','r'), (' ',' '), ('s','s')
# 例6-19
# 输入一段英文文本,统计出现频率最高的前 10个单词(除去 of,a,the 等无意义词语)
# 待处理的英文文本如下:
# I have a dream today!I have a dream that one day every valley shall be exalted,
# and every hill and mountain shall be made low,the rough places will
# be made plain, and the crooked places will be made straight; "and the glory of the Lord shall be
# revealed and all flesh shall see it together. This is our hope, and this is the faith that I go back to
# the South with.With this faith, we will be able to hew out of the mountain of despair a stone of
# hope. With this faith, we will be able to transform the jangling discords of our nation into a beautiful
# symphony of brotherhood. With this faith, we will be able to work together, to pray together, to
# struggle together, to go to jail together, to stand up for freedom
# together, knowing that we will be free one day.


# 观察这段文本,字母有大写有小写,还有一些标点符号
# 因此在统计单词出现频率之前需要先解决文本中大小写和标点符号的问题
# 所以,编写函数 getText()来对文本text进行预处理

# 预处理函数
# 先将所有字母换成小写
# 将文章中的 标点符号 都以空格代替

# 主体函数
# 将文本用split()函数分隔开,分成一个个单词
# 设一个空字典A用来存放单词 和 出现的次数
# 再处理 一些 无意义的词
# 创建一个包含 无意义的词 的字典B
# 遍历这个字典,在字典A中除去
# 然后 将字典A转换为列表,为了方便排序,以降序排列

def getText(text):

    text = text.lower()

    for ch in ", . : ! ? \'":
        text = text.replace(ch,' ')

    return text


def wordFreq(text,topn):

    word = text.split()

    a = {}
    for c in word:
        a[c] = a.get(c,0) + 1

    clear = {'the','to','of','a','be'}
    for word in clear:
        del(a[word])

    a = list(a.items())
    # print(a)
    a.sort(key = lambda x: x[1],reverse = True)

    return a[:topn]

text = '''I have a dream today! I have a dream that one day every valley shall be exalted,
and every hill and mountain shall be made low,the rough places will
be made plain, and the crooked places will be made straight; "and the glory of the Lord shall be
revealed and all flesh shall see it together. This is our hope, and this is the faith that I go back to
the South with.With this faith, we will be able to hew out of the mountain of despair a stone of
hope. With this faith, we will be able to transform the jangling discords of our nation into a beautiful
symphony of brotherhood. With this faith, we will be able to work together, to pray together, to
struggle together, to go to jail together, to stand up for freedom
together, knowing that we will be free one day.'''

text = getText(text)

for word,f in wordFreq(text,20):
    print('{:<10}{:>}'.format(word,f))


# will      6
# together  6
# and       5
# this      5
# shall     4
# faith     4
# with      4
# we        4
# i         3
# that      3
# made      3
# able      3
# have      2
# dream     2
# one       2
# day       2
# every     2
# mountain  2
# places    2
# is        2


# 下面这个 是 复习的时候 自己又重新写了一遍


# def f(s,n):
#     s = s.lower()
#     ls = s.split()
#     dic = {}
#     for i in ls :
#         dic[i] = dic.get(i,0) + 1
#     ls2 = [',' ,'.' ,':', '!', '?', '\'']
#     for i in ls:
#         del dic[i]      # 这里出错了 应该是先把标点符号用空格代替,再以空格把每个单词分开
                          # 而且这里原本的位置是 要删除一些无意义的词,前面的标点符号是预处理的,例题是写了两个函数
#     dic2 = sorted(dic,key = lambda x:dic[x],reverse=True)  # 这里也有问题  用这个sorted()返回的直接是列表
#     ls3 = list(dic.items())      # 这里就不能用这个列表转换了
#     for i in range(n+1):  # 这里的n也不用+1了,因为在列表遍历,本身从0开始的,0—19,本身就是20个数
#         print('{:<6}{:<6}'.format(ls3[i][0],ls3[i][1]))

# 下面是改正过的

def f(s,n):
    s1 = s.lower()
    ls = [',' ,'.' ,':', '!', '?', '\'']
    for i in ls:
        s2 = s1.replace(i,' ')
    ls2 = s2.split()
    dic = {}
    for i in ls2 :
        dic[i] = dic.get(i,0) + 1
    ls3 = ['the','to','of','a','be']
    for i in ls3:
        del dic[i]
    ls4 = sorted(dic.items(),key = lambda x:x[1],reverse=True)
    for i in range(n):                   # 这里的x 就是['()','()','()','()'...] 中的()
        print('{:<6}{:<6}'.format(ls4[i][0],ls4[i][1]))

f(text,20)

# will  6
# and   5
# this  5
# together,5
# shall 4
# we    4
# i     3
# that  3
# made  3
# faith,3
# able  3
# have  2
# dream 2
# one   2
# every 2
# mountain2
# places2
# is    2
# our   2
# go    2


# 不过,为啥两个运行出来的结果不一样
  • 13
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值