python程序设计基础答案第七章_Python语言程序设计基础(第2版) 课后题 第七章...

参考原版答案

import keyword

#7.1

stopwords = '\t\n\r: ()'

functionwords = '.('

word = []

output = ''

lastAvailable = ['from', 'import']

last = False

def readFile(path):

file = open(path,'r',encoding = 'utf-8')

string = file.read()

return string[1:]

def parse(string):

global last

global word

global output

for i in string:

if i in stopwords:

wd = ''.join(word)

res = isKeyWord(wd)

if res == False:

if i not in functionwords and last == False:

wd = wd.upper()

if wd in lastAvailable:

last = True

else:

last = False

output += wd

output += i

word = []

else:

word.append(i)

def isKeyWord(string):

if string in keyword.kwlist:

return True

return False

def outPutFile():

file = open('12.9.py','w',encoding = 'utf-8')

file.write(output)

string = readFile('test11.py')

parse(string)

outPutFile()

from PIL import Image

import os

import math

#7.2

def getsize(path):

return os.stat(path).st_size

def compress(path):

size = getsize(path)

ratio = math.sqrt(10*1024/size)

im = Image.open(path)

height = im.height;

width = im.width;

m_height = int(ratio*height)

m_width = int(ratio*width)

ph = im.resize((m_width, m_height))

ph.save('test_compressed.jpg',)

compress('birdnest.jpg')

#7.3

import json

f = open("price2016.csv",'r')

lister=[]

for line in f:

line = line.replace("[","")

line = line.replace("]","")

line = line.replace(" ","")

line = line.replace("\n","")

for i in line.split("'"):

if i != ',':

lister.append(i)

f2 = open('cityout.json','w')

for r in range(1,len(lister))

1b5d8

:

lister[r]=dict(zip(lister[0],lister[r]))

json.dump(lister[1:],f2,sort_keys=True,indent=4,ensure_ascii=False)

print('转换完成')

f2.close()

f.close()

转换完成

你可能感兴趣的:(python程序设计基础答案第七章_Python语言程序设计基础(第2版) 课后题 第七章...)