实验5 文件应用编程
task1_1.py
with open('data1_1.txt', 'r', encoding = 'utf-8') as f: data = f.readlines() n = 0 for line in data: if line.strip('\n') == '': continue n += 1 print(f'共{n}行')
task1_2.py
1 with open('data1_1.txt', 'r', encoding = 'utf-8') as f: 2 data = f.readlines() 3 4 n = 0 5 for line in data: 6 if line.strip('\n') == '': 7 continue 8 n += 1 9 print(f'共{n}行')
task1_3.py
1 with open('data1_2.txt', 'r', encoding = 'utf-8') as f: 2 n = 0 3 for line in f: 4 if line.strip() == '': 5 continue 6 n += 1 7 print(f'共{n}行')
task1_4.py
with open('data1_2.txt', 'r', encoding = 'utf-8') as f: n = 0 for line in f: if line.isspace(): continue n += 1 print(f'共{n}行')
task2.py
1 with open('data2.txt', 'r', encoding = 'utf-8') as f: 2 data = f.read().split('\n') 3 4 unique_line = [] 5 for line in data: 6 if data.count(line) == 1: 7 unique_line.append(line) 8 9 print(f'共{ len(unique_line) }独特行') 10 for i in unique_line: 11 print(i)
task3.py
1 with open('data3.txt','r',encoding='utf-8') as f : 2 with open('data3_processed.txt', 'w', encoding='utf-8') as f1: 3 data=f.read().strip().split('\n') 4 data.pop(0) 5 data1=[eval(i) for i in data] 6 data2=[] 7 for i in data1: 8 if i - int(i) >= 0.5: 9 data2.append(int(i) + 1) 10 else: 11 data2.append(int(i)) 12 data3=[int(i)for i in data2] 13 f1.write(f'原始数据\t四舍五入后的数据\n') 14 for j in range(len(data)): 15 f1.write(f'{data1[j]}\t\t{data2[j]}\n') 16 print(f'原始数据:\n{data1}\n四舍五入后的数据:\n{data2}')
task4.py
1 with open('data4.txt','r',encoding='utf-8')as f: 2 with open('data4_processed.txt','w',encoding='utf-8')as f1: 3 data=f.readlines() 4 data1=[i.strip('\n').split('\t') for i in data] 5 x=data1.pop(0) 6 data2=[sorted(data1,key=lambda x: (x[2], -int(x[3])))] 7 print('\t\t'.join(x)) 8 f1.write('\t\t'.join(x)+'\n') 9 for i in data2: 10 for j in i: 11 print('\t'.join(j)) 12 f1.write('\t'.join(j)+'\n')
task5.py
1 with open('data5.txt','r',encoding='utf-8')as f: 2 with open('data5_with_line.txt', 'w', encoding='utf-8') as f1: 3 a=f.read().strip('\n') 4 b = len(a.splitlines()) 5 print('行数:', b) 6 e = len(a.split()) 7 print('单词数:', e) 8 c = 0 9 for c, number in enumerate(a): 10 c += 1 11 print('字符数:', c) 12 d = 0 13 for i in a: 14 if i == ' ': 15 d += 1 16 print('空格数:', d) 17 a=a.split('\n') 18 n='\n'.join(a)