实验4

#统计文件data1_1.txt的行数(不包括空白行)
#data1_1中的空白行都是由\n组成的空白行
#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}行')

 

 

#统计文件data1_2.txt的行数(不包括空白行)
#data1_2中的空白行包括空格、tab键、换行键构成的空白行
# #task1_3.py
with open('data1——2.txt','r',encoding='utf-8') as f:
n=0
for line in f:
if line.strip()=='':
continue
n+=1
print(f'共{n}行')

 

#task1_3.py
with open('data1_2.txt','r',encoding='utf-8') as f:
n=0
for line in f:
if line.strip()=='':
continue
n+=1
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.issapce()=='':
continue
n+=1
print(f'共{n}行')

 

 

#实验任务2:统计独特行的行数
with open('data2.txt','r',encoding='utf-8') as f:
data=f.read().split('\n')
unique_line=[]
for line in data:
if data.count(line)==1:
unique_line .append(line)
print(f'共{len(unique_line)}行独特行')
for i in unique_line:
print(i)

 

 

#不使用csv模块,使用Python的内置读写操作进行csv的读写
#把两维列表中的数据写入csv格式的文件data3.csv中
#task3.py
ls=[['城市','大致人口'],
['南京','850万'],
['纽约','2300万'],
['东京','3800万'],
['巴黎','1000万']]
with open('data3.csv','w',encoding='utf-8') as f:
for line in ls:
data=','.join(line)+'\n'
f.write(data)
#从data3.csv中读取数据,把逗号替换成\t,分行打印输出到屏幕上
with open('data3.csv','r',encoding='utf-8') as f:
data=f.read()
print(data.replace(',','\t'),end='')

 

 

#实验任务4:csv格式文件读写基本操作
#使用csv模块进行csv格式的读写
#把两维列表中的数据写入csv格式的文件data4.csv中
#task4.py
import csv
ls=[['城市','大致人口'],
['南京','850万'],
['纽约','2300万'],
['东京','3800万'],
['巴黎','1000万']]
with open('data4.csv','w',encoding='utf-8',newline='') as f:
writer=csv.writer(f)
writer.writerows(ls)
with open('data4.csv','r',encoding='utf-8') as f:
reader=csv.reader(f)
for line in reader:
print('\t'.join(line))

 

 任务5-2

 

 任务5-1

 

with open('data6_1.txt','r',encoding='utf-8') as f:
data = f.read().split('\n')
data1 = [str(i).split('\t') for i in data]
f=lambda x:x[2]
data1.sort(key=f, reverse=True)
with open('data2.txt', 'w+',encoding='utf-8') as f1:
for line in data1:
for i in line:
f1.write(i + '\t')
print(i + '\t', end='')
f1.write('\n')

 

 

import datetime
t = datetime.datetime.now()
t = t.strftime('%Y%m%d')
import random
with open('data7.txt', 'r', encoding='gbk')as f:
data = f.read().split('\n')
info = eval(input('输入随机抽点人数:'))

output = set()
while len(output) < info:
rand = random.randint(0, len(data) - 1)
output.add(str(data[rand]))

with open(f'{t}.txt', 'w+', encoding='utf-8')as f:
for line in output:
f.write(line + '\n')
print(line)

 

posted @ 2021-05-12 19:24  叹之  阅读(89)  评论(1编辑  收藏  举报