找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 3420|回复: 2

《head first python》的例题疑问

1

主题

1

帖子

5

积分

贫民

积分
5
nashchi 发表于 2014-7-26 09:58:04 | 显示全部楼层 |阅读模式
1.neser.py

import sys

def print_lol(the_list, indent=False, level=0, fh=sys.stdout):
    for item in the_list:
         if isinstance(item, list):
             print_lol(item, indent, level+1, fh)
         else:
             if indent:
                 for num in range(level):
                     print fh,"\t"
             print fh,item


2.dayin.py


import nester
from nester import 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)
            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:
    print 'File error'


我仔细对照了教材,并无差错,唯独print用法,因为我是2.7的python,教材是3.0,做了调整,但是就是没办法从sketch.txt里读取并输出到另2个txt中。



回复

使用道具 举报

0

主题

6

帖子

6

积分

贫民

积分
6
chaoshui 发表于 2014-7-29 14:15:58 | 显示全部楼层
neser.py中最后一行

print fh,item  加上个>>改成 print >>fh,item
回复 支持 反对

使用道具 举报

0

主题

20

帖子

20

积分

贫民

积分
20
赵大班长1 发表于 2014-7-29 15:07:07 | 显示全部楼层
import nester
from nester import print_lol
这个位置的名字写错了吧,跟上面的不相同,
请给出txt文档的样式看一下,应该有Man: 和 Other Man:这样的文字吧
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表