1,p124,错误:NameError: name 'print_lol' is not defined
要想文件内如图显示,需要把调用BIF print()改为调用第二章的nester模块中的print_lol()函数,因此需要导入nester模块。
首先需要修改第二章nester模块中的print_lol()函数并更新该模块,更新方法如图:
然后在sketch.py中调用print_lol()函数。
'''
修改时间:0919
修改内容:把调用BIF print()改为调用第二章的nester模块中的print_lol()函数,需要导入nester模块
'''
import nester man=[]
other=[]
try:
data=open('sketch.txt')
for each_line in data:
try:
(role,line_spoken)=each_line.split(':',1)
line_spoken=line_spoken.strip()
if role=='Man':
man.append(line_spoken)
elif role=='Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print('The datafile is missing!') try:
with open('man_data.txt','w') as man_file,open('other_data.txt','w') as other_file:
print_lol(man,fh=man_file)
print_lol(other,fh=other_file)
except IOError as err:
print('File Error:'+str(err))
这时会报错:
原因:
调用模块的函数时,格式为“模块名.函数名()”
因此代码更改为:
'''
修改时间:0919
修改内容:把调用BIF print()改为调用第二章的nester模块中的print_lol()函数,需要导入nester模块
注意:调用print_lol时,需要把模块名加上,nester.print_lol(),而不是直接调用print_lol().
'''
import nester man=[]
other=[]
try:
data=open('sketch.txt')
for each_line in data:
try:
(role,line_spoken)=each_line.split(':',1)
line_spoken=line_spoken.strip()
if role=='Man':
man.append(line_spoken)
elif role=='Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print('The datafile is missing!') try:
with open('man_data.txt','w') as man_file,open('other_data.txt','w') as other_file:
nester.print_lol(man,fh=man_file)
nester.print_lol(other,fh=other_file)
except IOError as err:
print('File Error:'+str(err))
2. pickle模块中dump()和load()的用法
dump()保存数据,load()恢复数据,即下载数据
try:
with open('man_data.txt','wb') as man_file,open('other_data.txt','wb') as other_file:
pickle.dump(man,man_file)
pickle.dump(other,other_file)
except pickle.PickleError as perr:
print('Pickling Error:'+str(perr))
import pickle
import nester
new_name=[]
try:
with open('man_data.txt','rb')as man_file:
new_name=pickle.load(man_file)
except IOError as err:
print('File error:'+str(err))
except pickle.PickleError as perr:
print('Pickling Error:'+str(perr)) nester.print_lol(new_name)