3-18作业
1、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作
1 def replace_file(src, **kwargs):
2 import os
3 if not os.path.exists(r'{}'.format(src)):
4 print("当前路径下无文件")
5 return
6 with open(r'{}'.format(src), 'rb') as r,\
7 open(r'{}.swap'.format(src), 'wb') as w:
8 for line in r:
9 line = line.decode('utf-8')
10 if kwargs['old_content'] in line:
11 w.write(line.replace(kwargs['old_content'], kwargs['new_content']).encode('utf-8'))
12 else:
13 w.write(line.encode('utf-8'))
14 os.remove('{}'.format(src))
15 os.rename('{}.swap'.format(src), '{}'.format(src))
16
17 inp_src = input('输入文件名:').strip()
18 old_content = input("要修改的内容:").strip()
19 new_content = input("修改后的内容:").strip()
20 replace_file(inp_src, old_content=old_content, new_content=new_content)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def change_file(file_path, old, new): ''' :param file_path: 修改的文件路径 :param old: 要修改的内容 :param new: 修改后的内容 :return: ''' list1 = [] with open(file_path, 'r', encoding='utf-8') as f: # 如果文件比较大的时候,用for循环一行一行读取更好 for line in f: line = line.replace(old, new) # old:tank3, new: egon list1.append(line) # 执行到此处,操作系统已经回收打开文件的资源 with open(file_path, 'w', encoding='utf-8') as f: for line in list1: f.write(line) change_file('test.txt', 'tank1', 'egon')
2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
1 def count(*args):
2 dic = {
3 'num': 0,
4 'alpha': 0,
5 'space': 0,
6 'others': 0
7 }
8 for i in args:
9 if i.isdigit():
10 dic['num'] += 1
11 elif i.isalpha():
12 dic['alpha'] += 1
13 elif i.isspace():
14 dic['space'] += 1
15 else:
16 dic['others'] += 1
17 return dic
18
19
20 ipt = input('input something:')
21 res = count(*ipt)
22 print(res)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def count(str1): ''' :param str1: 外部传入的字符串,字符串由数字、字母、空格、其他字符组成 :return: ''' # 1) 初始化每种字符类型的个数 dic = { 'number': 0, # 数字个数 'letters': 0, # 字母个数 'blank': 0, # 空格个数 'other': 0, # 其他个数 } # 2) 循环遍历,检测每个字符的类型,并为其添加个数 for line in str1: # a123 # 3) 判断字符串是否是数字、字母、空格、其他 if line.isdigit(): dic['number'] += 1 elif line.isalpha(): # 判断line是否是字母 dic['letters'] += 1 # elif line == ' ': elif line.isspace(): # 判断是否是空格 dic['blank'] += 1 else: dic['other'] += 1 return dic res = count('tank 123 egon_sb 321 !@@#¥%(())**&%……¥') print(res)
3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
1 def object_len(obj):
2 if len(obj) < 5:
3 print('长度小于5')
4 elif len(obj) > 5:
5 print('长度大于5')
6 else:
7 print('长度等于5')
8
9 object_len(('今天3-18','岁月是一场有去无的旅行',{'name':'tank','age':'18'},['egon','alex']))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def check_length(str_list_tuple): if len(str_list_tuple) > 5: print(f'{str_list_tuple}的长度大于5') else: print('太短了,不行!') check_length('egon_sb_10')
4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def check_list(list1): # len: 用于获取所有 "序列" 类型的长度 # 序列: str, list, tuple, set if len(list1) > 2: return list1[:2] # 0,1 res = check_list(['tank', 'egon_sb', 'egon']) print(res)
5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def get_odd_element(list_tuple): # [1, 2, 3, 4, 5, 6] # 索引: 0 1 2 3 4 5 return list_tuple[1::2] res = get_odd_element([1, 2, 3, 4, 5, 6]) print(res)
6、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
PS:字典中的value只能是字符串或列表
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
def check_dict(dic):
for key, value in dic.items():
if len(value) > 2:
dic[key] = value[:2] # 0, 1
return dic
dic = {"k1": "v1v1", "k2": [11, 22, 33, 44]}
res = check_dict(dic)
print(res)