3.18---函数应用

1、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作

#法一:存在缺陷,传入旧值必须符合变量命名规则
def change_name(file_name, **kwargs):
    '''传入需要修改的文件名,并以keyword(旧字符)= value(新字符)形式传入需要修改的内容'''
    import os
    for key in kwargs:
        old = key
        new = kwargs[key]
        with open(rf"{file_name}",mode="rt",encoding="utf-8") as f,\
            open(r".new_swap.txt",mode="wt",encoding="utf-8") as f1:
            for line in f:
                new_line = line.replace(old,new)
                f1.write(new_line)
        os.remove(rf"{file_name}")
        os.rename(r".new_swap.txt",rf"{file_name}")
change_name("a.txt",n="1",b="2")

#法二:新旧交替传入,虽然旧值无限制,但需更改值较多时,易混淆新旧值
def change_name2(file_name,*args):
    import os
    if len(args) % 2 == 1:
        print("输入参数个数有误!")
        return
    for i in range(len(args)):
        if i % 2 == 0:
            with open(rf"{file_name}",mode="rt",encoding="utf-8") as f,\
                open(r".new.swap.txt",mode="wt",encoding="utf-8") as f1:
                for line in f:
                    new_line = line.replace(args[i],args[i+1])
                    f1.write(new_line)
            os.remove(rf"{file_name}")
            os.rename(r".new.swap.txt",rf"{file_name}")
change_name2("a.txt","a","b","c","d")

 

2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数

def count(*args):
    dic = {}
    l = ["数字","字母","空格","其他"]
    for s_str in args:
        dic[s_str] = {}.fromkeys(l,0)
        s_l = list(s_str)
        for elm in s_l:
            if "9" >= elm >= "0":
                dic[s_str]["数字"] += 1
            elif "z" >= elm >= "a" or "Z" >= elm >= "A":
                dic[s_str]["字母"] += 1
            elif elm == " ":
                dic[s_str]["空格"] += 1
            else:
                dic[s_str]["其他"] += 1
        print(f"{s_str}:\t{dic[s_str]}")

count("Who are you, 9527?","I'm your father!")
"""
Who are you, 9527?:    {'数字': 4, '字母': 9, '空格': 3, '其他': 2}
I'm your father!:    {'数字': 0, '字母': 12, '空格': 2, '其他': 2}
"""

3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。

def length_5(*args):
    print("长度是否大于5".center(50,"-"))
    dic = {}
    for elm in args:
        if str(type(elm)) in ("<class 'dict'>", "<class 'list'>", "<class 'str'>"):
            if len(elm) >= 5:
                if str(type(elm)) == "<class 'list'>" or str(type(elm)) == "<class 'dict'>":
                    dic[str(elm)] = True
                else:
                    dic[elm] = True
            else:
                if str(type(elm)) == "<class 'list'>" or str(type(elm)) == "<class 'dict'>":
                    dic[str(elm)] = False
                else:
                    dic[elm] = False
        else:
            print(f"不可输入{type(elm)}类型")
            return
    for key in dic:
        print(f"{key}:{dic[key]}")

length_5("aaa","bbb")
"""
---------------------长度是否大于5----------------------
aaa:False
bbb:False
"""

4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

def check_length(c_list):
    if str(type(c_list)) in ( "<class 'list'>", "<class 'str'>"):
        if len(c_list) > 2:
            if str(type(c_list)) == "<class 'list'>":
                new_list  = [c_list[0],c_list[1]]
            else:
                new_list = c_list[0:2]
            return new_list
        else:
            return c_list
    else:
        print(f"不可输入{type(c_list)}类型")

l = {}
l = check_length(l)
print(l)                                                        # [1, 2]

5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。

def odd_index(lt):
    new_l = []
    # if not lt:
    for i in range(len(lt)):
        if i % 2 == 0:
            new_l.append(lt[i])
    return new_l
print(odd_index([1,2,3,4,5,]))                                  # [1, 3, 5]

 

6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

dic = {"k1": "v1v1", "k2": [11,22,33,44]}

PS:字典中的value只能是字符串或列表

def check_dic(dic_2):
    for key in dic_2:
        dic_2[key] = check_length(dic[key])
    return dic_2

print(check_dic(dic))

 

posted @ 2020-03-18 16:30  Jil-Menzerna  阅读(149)  评论(0编辑  收藏  举报