首页 > 编程语言 >实验5 文件应用编程

实验5 文件应用编程

时间:2023-06-06 19:33:58浏览次数:37  
标签:count 文件 encoding open 编程 datetime 实验 print data

task 6

源代码

 

with open('data6.csv', 'r', encoding='gbk') as f:
   data = f.readlines()
   data.pop(0)
   data = [eval(i.strip()) for i in data]
print(f'原始数据:\n{data}')

processed_data = [int(i+0.5) for i in data]
print(f'四舍五入后数据:\n{processed_data}')


import csv
title = ['原始数据', '四舍五入后数据']
with open('data6_processed.csv', 'w', encoding='gbk') as f:
    f_writer = csv.writer(f)
    f_writer.writerow(title)
    info = list(zip(data, processed_data))
    f_writer.writerows(info)

 

测试结果

 

 

task7

源代码

with open('data7.csv', 'r', encoding='gbk') as f:
    data = f.readlines()
    data = [i.strip().split(',') for i in data]
title = data[0]
data.pop(0)


data1 = sorted(data, key=lambda x: (x[2], -int(x[3])))
print(data1)
for i in title:
    print('{:18}'.format(i), end='')
print('\n')
for i in data1:
    print('{:<18}'.format(i[0]), '{:<18}'.format(i[1]), '{:<18}'.format(i[2]), '{:<18}'.format(i[3]))

import csv
with open('data7_processed.csv', 'w', encoding='utf-8') as f:
    f_writer = csv.writer(f)
    f_writer.writerow(title)
    f_writer.writerows(data1)

测试结果

 

 

task8

源代码

 

lines_count, words_count, char_count, blanks_count = 0, 0, 0, 0
text = []
with open('hamlet.txt', 'r', encoding='utf-8') as f:
    for line in f:
        words = line.split()
        lines_count += 1
        words_count += len(words)
        char_count += len(line)
        for i in line:
            if i == ' ':
                blanks_count += 1
        text.append(line)
print('hamlet.txt粗略统计')
print('行数:', lines_count)
print('单词数:', words_count)
print('字符数:', char_count)
print('空格数:', blanks_count)

newtext = []
n = 0
while n < len(text):
    newtext.append(str(n+1) + ' ' + text[n])
    n += 1

with open('hamlet_with_line_number.txt', 'w', encoding='utf-8') as f:
    for i in newtext:
        f.write(i)

 

测试结果

 

task9

源代码

def is_valid(x):
    if len(x) == 18 and x[:-2:].isnumeric():
        if x[-1] == 'X' or x[-1].isnumeric():
            return True
        else:
            return False
    else:
        return False

with open('data9_id.txt', 'r', encoding='utf-8') as f:
    data = f.readlines()
    data.pop(0)
data = [i.strip().split(',') for i in data]

import datetime
t = datetime.datetime.now()
year = int(t.strftime('%Y'))


data1 = []
for i in data:
    if is_valid(i[1]) is True:
        age = year-int(i[1][6:10])
        i[1] = i[1][6:10]+'-'+i[1][10:12]+'-'+i[1][12:14]
        i.append(str(age))
        data1.append(i)
data2 = sorted(data1, key=lambda x:-int(x[2]))

print('{:10}'.format('姓名')+'{:12}'.format('出生日期')+'{:10}'.format('年龄'))
for i in data2:
    print('{:<10}'.format(i[0])+'{:<15}'.format(i[1])+'{:<10}'.format(i[2]))

 

测试结果

 

task10-1

源代码

 

with open('data10_stu.txt', 'r', encoding='utf-8') as f:
    data = f.readlines()

import random
import datetime
n = int(input('输入随机抽点人数:'))
t = datetime.datetime.now()
filename = t.strftime('%Y%m%d')

for i in range(n):
    print(data[random.randint(1, len(data))])
with open('{}.txt'.format(filename), 'w', encoding='utf-8') as f:
    for i in range(n):
        f.write(data[random.randint(1, len(data))])

 

 

测试结果

 

 

task10-2

 

源代码

 

with open('data10_stu.txt', 'r', encoding='utf-8') as f:
    data = f.readlines()

import random
import datetime

t = datetime.datetime.now()
filename = t.strftime('%Y%m%d')
with open('{}*.txt'.format(filename), 'w', encoding='utf-8') as f:
    while True:
        n = int(input('输入随机抽点人数:'))
        for i in range(n):
            k = random.randint(1, len(data))
            print(data[k])
            f.write(data[k])
            data.pop(k)

        if n == 0:
            break

 

测试结果

 

标签:count,文件,encoding,open,编程,datetime,实验,print,data
From: https://www.cnblogs.com/tyy2004/p/17461494.html

相关文章

  • 日志文件中按照日期搜索
    近期经常遇到故障,需要在message文件中,定位时间点的日志。因此总结了几个常用的实用命令1、使用sed命令定位sed'/Sep1808/,/Sep1811/p'/var/log/messagescat/var/log/messages|grep-E'Sep1809|Sep1811'2、使用日期的date命令定位[ttmonitor007@~]$dateFriMay19......
  • 实验5 文件应用编程
    实验5文件应用编程实验任务6: task6.py1withopen('data6.csv','r',encoding='gbk')asf:2old_data=f.read().split('\n')3delold_data[0]4processed_data=[]5foriinrange(len(old_data)):6ifeval(ol......
  • 实验5 文件应用编程
    task6源代码:withopen('data6.csv','r',encoding='gbk')asf:old_data=f.read().split('\n')delold_data[0]new_data=[]foriinrange(len(old_data)):ifeval(old_data[i])+float(0.5)>=int(eval(o......
  • 实验五
    task6源代码:withopen('data6.csv','r',encoding='gbk')asf:data=f.readlines()data.remove('原始数据\n')data1=[]foriindata:ifi[-1]=='\n':i=i[:-1]data1.append(float(i))print(&#......
  • 实验5 文件应用编程
    实验任务61withopen('data6.csv','r',encoding='gbk')asf:2old_data=f.read().split('\n')3delold_data[0]4processed_data=[]5foriinrange(len(old_data)):6ifeval(old_data[i])+0.5>=......
  • 特殊文件、日志技术概括
       ......
  • 实验5
    task6withopen('data6.csv','r',encoding='gbk')asf:old_data=f.read().split('\n')delold_data[0]processed_data=[]foriinrange(len(old_data)):ifeval(old_data[i])+0.5>=int(eval(old_data......
  • docker 操作nginx命令+docker-compose常用命令及yml文件编写
    docker-compose常用命令及yml文件编写https://blog.csdn.net/doubiy/article/details/118997661 https://docs.docker.com/compose/1.观察下载容器镜像过程dockerrun-dnginx:latest-d表示当前终端的后台运行nginx:latest就是最新的nginx版本2.访问容器中的ngi......
  • Idea修改html文件不需重启
    1.首先设置为自动编译“File”->“Settings”->“Build,Execution,Deplyment”->“Compiler”2.允许运行时自动编译“Shift+Ctrl+Alt+/”,选择“Registry”,选中打勾“compiler.automake.allow.when.app.running”......
  • 实验5
    task61withopen('data6.csv','r',encoding='gbk')asf:2old_data=f.read().split('\n')3delold_data[0]45new_data=[]6foriinrange(len(old_data)):7ifeval(old_data[i])+float(0.5)......