1. 定义一个print_lol函数来控制列表的缩进和写入位置
import sys
"""this is a new fuction, which work for a list"""
def print_lol(the_list,indent=False,level=0,where=sys.stdout):
""" one arguement is the_list"""
for each_item in the_list:
if isinstance(each_item,list):
print_lol(each_item,indent,level+1,where)
else:
if indent:
for tab_stop in range(level):
print(" ",end='',file=where)
print(each_item,file=where)
2. 将更新的代码安装到本地库
C:UsersericDocumentsPython ester>c:UsersericAppDataLocalProgramsPythonPython35-32python.exe setup.py install running install running build running build_py copying nester.py -> buildlib running install_lib copying buildlib ester.py -> c:UsersericAppDataLocalProgramsPythonPython35-32Libsite-packages byte-compiling c:UsersericAppDataLocalProgramsPythonPython35-32Libsite-packages ester.py to nester.cpython-35.pyc running install_egg_info Removing c:UsersericAppDataLocalProgramsPythonPython35-32Libsite-packagesiamericnester-1.6.1-py3.5.egg-info Writing c:UsersericAppDataLocalProgramsPythonPython35-32Libsite-packagesiamericnester-1.6.1-py3.5.egg-info
3. 前段代码格式化文件内容并分割将内容存入man和other两个对象,后段代码以写模式打开2个新的文件并man和other对象存入其中。(存入的过程中调用print_lol进行格式再处理)
import nester
import sys
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 datafiel is missing!')
try:
with open('man_data.txt','w') as man_file:
nester.print_lol(man,where=man_file)
with open('other_data.txt','w') as other_file:
nester.print_lol(other,where=other_file)
except IOError as err:
print('file error:' +str(err))