作业 —— day14

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

def update(address, **kwargs):
    import os
    if not os.path.exists(r'{}'.format(address)):
        print('当前路径下不存在该文件!')
        return
    with open(r'{}'.format(address), mode='rb') as r, \
            open(r'{}.swap'.format(address), mode='wb') as w:
        for line in r:
            line = line.decode('utf-8')
            if kwargs['old_content'] in line:
                w.write(line.replace(kwargs['old_content'], kwargs['new_content']).encode('utf-8'))
            else:
                w.write(line.encode('utf-8'))
    os.remove('{}'.format(address))
    os.rename('{}.swap'.format(address), '{}'.format(address))


address = input('请输入文件名:').strip()
old_content = input('请输入要修改的内容:').strip()
new_content = input('请输入修改后的内容:').strip()

update(address, old_content=old_content, new_content=new_content)

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

def count_some():
    num = 0
    letter = 0
    space = 0
    other = 0
    inp_str = input('请输入要检测的字符串:')
    for line in inp_str:
        if line.isdigit():
            num += 1
        elif 65 <= ord(line) <= 90 or 97 <= ord(line) <= 122: # 在ASCII码表中,A-Z对应65-90,a-z对应97-122
            letter += 1
        elif ord(line) == 32:   # 在ASCII码表中,32对应空格(space)
            space += 1
        else:
            other += 1
    print('数字{}个\n字母{}个\n空格{}个\n其他字符{}个'.format(num,letter,space,other))

count_some()

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

def morethan_five():
    inp_sth = input('请输入要检测的对象:')
    if inp_sth.startswith('[') and inp_sth.endswith(']'):
        inp_sth = inp_sth.strip('[').strip(']').replace(',','')
        res = len(inp_sth)
    elif inp_sth.startswith('(') and inp_sth.endswith(')'):
        inp_sth = inp_sth.strip('(').strip(')').replace(',', '')
        res = len(inp_sth)
    else:
        res = len(inp_sth)
    print(res)

morethan_five()

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

def morethan_two(x, y, *args):
    return x, y
x, y = morethan_two(*[1, 2, 3, 4, 5, '6'])
print(x,y)

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

def return_single(old_list):
    if type(old_list)==list or type(old_list)==tuple:
        new_list = []
        for i in old_list:
            if  old_list.index(i)%2 == 1:
                new_list.append(i)
    else:
        print("输入的类型不是列表或元组,请重新输入!")
    return new_list
res = return_single([1,2,3,4,5])
print(res)

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

dic = {"k1": "v1v1", "k2": [11,22,33,44]}
PS:字典中的value只能是字符串或列表

dic = {"k1": "v1v1", "k2": [11,22,33,44]}
def morethan_two_plus(a):
    for i in a:
        if len(a[i]) > 2:
            a[i] = a[i][0:2]
    return a
res = morethan_two_plus(dic)
print(res)
posted @ 2020-03-18 22:50  轻描丨淡写  阅读(186)  评论(0编辑  收藏  举报