python 基础教程第三版 -- 第十章 开箱即用 == 使用 fileinput 处理多个文件

# 创建模板处理系统 
(python_scripts) [root@mha-1 python_scripts]# cat template.py 
import fileinput, re 

# 与使用方括号扩起来的字段匹配 
field_pat = re.compile(r'\[(.+?)\]') 

# 让我们把变量收集到这里: 
scope = {} 


# 用于调用 re.sub 
def replacement(match): 
    code = match.group(1) 
    try: 
        # 如果字段为表达式,就返回其结果 
        return str(eval(code, scope)) 
    except SyntaxError: 
        # 否则在当前作用域内执行该赋值语句 
        exec(code, scope) 
        # 并返回一个空字符串 
        return '' 


# 获取所有文本合并成一个字符串 
lines = [] 
for line in fileinput.input(): 
    lines.append(line) 
text = ''.join(lines) 

# 替换所有与字段模式匹配的内容: 
print(field_pat.sub(replacement, text)) 

# 创建定义文件 
(python_scripts) [root@mha-1 python_scripts]# cat magnus.txt [name = 'Magnus Lie Hetland'] 
[email = 'magnus@foo.bar'] 
[language = 'python'] 

# 创建模板文件 
(python_scripts) [root@mha-1 python_scripts]# cat template.txt 
[import time] 
Dear [name], 

I would like to learn how to program.I hear you 
use the [language] language a log -- is it somethis I 
should consider? 

And, by the way,is [email] your correct email address? 
Fooville,[time.asctime()] 

Oscar Frozzbozz 

# 使用定义文件和模板文件生成最终的想要的效果 

(python_scripts) [root@mha-1 python_scripts]# python template.py magnus.txt template.txt                           

Dear Magnus Lie Hetland, 

I would like to learn how to program.I hear you 
use the python language a log -- is it somethis I 
should consider? 

And, by the way,is magnus@foo.bar your correct email address? 
Fooville,Mon Jan 27 20:21:17 2020 

Oscar Frozzbozz 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值