调用定制的文件处理函数print_lol处理输出的文件man_data 和 other_data

1.修改print_lol增加一个参数space

'''这是一个"nesterliz001.py"文件提供了一个名为print——lol()的函数,这个函数的作用是打印列表,其中有可能
包含(也可能不包含)嵌套列表。'''
import sys
def print_lol(the_list, indent=False, level=0, space=sys.stdout):    #sys.stdout为默认值
    '''这个函数取一个位置参数,名为'the_list',这可以是任何pytho列表(也可以是包含嵌套列表的列表)。所指定的列表中的每个数据项会(递归地)输出到屏幕上,各数据项各占一行,且在遇到新的列表是自动缩进,'''
    
#增加了space参数,是print_lol()可以被调用
    for each_item in the_list:
            if isinstance(each_item, list):
                print_lol(each_item, indent, level+1, space )
            else:
                if indent:
                    for tab_stop in range(level):
                        print("\t",end='', file=space)
                print(each_item, file=space)


#print_lol(name,True)

2.调用print_lol函数,将man_data 和other_data 格式化输出

from nester_liz001 import print_lol     #调用print_lol函数
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)      #将man的话添到man[]
               
            elif role == 'Other Man':       
               other.append(line_spoken)        #将other man的话添到列表
           
             

       
        except ValueError:      #异常处理
            pass
    if 'data' in locals():      #调用方法locals()判断‘data’文件是否存在当前环境中
        data.close()
    



except IOError:     #I/O错误处理
    print('The data file is missing!')

#将处理的数据写入man1.txt和other2.txt文档


try:
    with open('man_data.txt', 'w') as man_data:
        print_lol(man, space=man_data)
    with open('other_data.txt', 'w') as other_data:
        print_lol(other, space=other_data)
except IOError as err:
    print('file error:' + str(err))

 

posted @ 2018-08-24 21:33  nester_liz  阅读(173)  评论(0编辑  收藏  举报