基本信息
文件名称:实验五:文件和数据格式.docx
文件大小:465.29 KB
总页数:6 页
更新时间:2025-06-11
总字数:约2.25千字
文档摘要

姓名

实验时间

指导教师

成绩

实验项目名称

文件和数据格式

实验目的

掌握文件的读写方法以及打开和关闭等基本操作;

理解数据组织的维度和特点;

掌握一、二维数据的存储格式和读写方法;

运用PIL库进行基本的图像处理;

运用json库进行数据的维度转换;

了解高维数据的存储格式和读写方法

掌握文件的基本操作,使用json库进行数据转换

实验内容

图像的字符画绘制:将图像转换为字符画形式。

fromPILimportImage

defimage_to_ascii(image_path,output_width=150):

image=Image.open(image_path)

width,height=image.size

output_height=int(height*output_width/width)

image=image.resize((output_width,output_height))

ascii_chars=***###...

ascii_image=

foryinrange(output__height):

forxinrange(output_width):

r,g,b=image.getpixel((x,y))

gray=int(0.2126*r+0.7152*g+0.0722*b)

ascii_image+=ascii_chars[gray//32]

ascii_image+=\n

returnascii_image

image_path=lanYangYang.jpg

ascii_image=image_to_ascii(image_path)

print(ascii_image)

运行结果原图

2.编写程序将CSV格式文件与ison文件格式互相转换

#e14.1csv2json.py

importjson

fr=open(Python2.csv,r,encoding=utf-8

1s=[]

forlineinfr:

line=line.replace(\n,))

ls.append(line.split(,))

fr.close()

fw=open(Python2.json,w,encord=utf-8)

foriinrange(1,len(1s)):

1s[i]=dict(zip(1s[0],1s[i]))

json.dump(1s[1:],fw,sort_keys=Ture,indent=4fw.close)

#14.2json2csv.Py

importjson

importcsv

defjson_to_csv(json_file,csv_file):

withopen(json_file,r,encoding=utf-8)asf:

data=json.load(f)

ifnotdata:

print(JSON文件为空,无法转换。)

return

headers=data[0].keys()

withopen(csv_file,w,newline=,encoding=utf-8)asf:

csv_writer=csv.DictWriter(f,fieldnames=headers)

csv_writer.writeheader()

csv_writer.writerows(data)

print(f转换完成!已将{json_file}转换为{csv_file})

print(\n以下是生成的CSV文件内容预览:)

withopen(csv_file,r,encoding=utf-8)asf:

fori,lineinenumerate(f):

ifi=5:

break

print(line.strip())

json_to_csv(price2016.json,price2016.csv)

实验总结

通过Python编程实现了图像转换为A