• [Head First Python]4.读取文件datafile.txt, 去除两边空格, 存储到列表,从列表格式化(nester.py)后输出到文件man.out,other.out


    datafile.txt  #文件

    Man: this is the right room for an argument.
    Other Man: I've told you once.
    Man: No you haven't
    Other Man: Yes, I have.
    (pause)
    Man: When?
    Other Man: Just now.
    Man: No you didn't
    Other Man: Yes I did.
    Man: You didn't
    Other Man: I'm telling you, I did!

    nester.py #输出模块 第2章文件nester.py修改后的模块,安装到你的python环境中

    1 def print_lol(the_list, indent = False, level = 0, fn = sys.stdout):
    2     for each_item in the_list:
    3         if isinstance(each_item,list):
    4             print_lol(each_item, indent, level + 1, fn);
    5         else:
    6             if indent:
    7                 for tab_stop in range(level):
    8                     print("	",end='', file = fn)
    9             print(each_item, file = fn)

    sketch.py #读取文件datafile.txt, 去除两边空格, 存储到列表,从列表格式化(nester.py)后输出到文件man.out,other.out

     1 import nester
     2 man = []
     3 other = []
     4 try:
     5     data = open ("datafile.txt")
     6 
     7     for each_line in data:
     8         try:
     9             (role, line_spoken) = each_line.split(":", 1)
    10             line_spoken = line_spoken.strip()
    11             if role == 'Man':
    12                 man.append(line_spoken)
    13             elif role == 'Other Man':
    14                 other.append(line_spoken)
    15 
    16         except ValueError:
    17             pass
    18 
    19     data.close()
    20 except IOError:
    21     print('this data file is missing!')
    22 
    23 try:
    24     with open('man.out', 'w') as man_out, open('other.out','w') as other_out:
    25         nester.print_lol(man, fn = man_out)
    26         nester.print_lol(other, fn = other_out)
    27 
    28 except fileError as err:
    29     print('file error' + str(err)) 

     man.out

    this is the right room for an argument.
    No you haven't
    When?
    No you didn't
    You didn't

    other.out

    I've told you once.
    Yes, I have.
    Just now.
    Yes I did.
    I'm telling you, I did!
  • 相关阅读:
    Android应用程序注冊广播接收器(registerReceiver)的过程分析
    智能生活 “视”不可挡——首届TCL杯HTML5智能电视开发大赛等你来挑战
    点滴的积累---J2SE学习小结
    公开课
    iOS学习之 plist文件的读写
    【STL】关联容器 — hash_set
    《Pro Android Graphics》读书笔记之第三节
    第一章. ActionScript 语言基础
    JAVA数组的定义及用法
    MS-SQLSERVER中的MSDTC不可用解决方法
  • 原文地址:https://www.cnblogs.com/galoishelley/p/3793096.html
Copyright © 2020-2023  润新知