一个模版系统
这是程序:
#!/usr/bin/env python
# templates.py
import fileinput, re
# Match strings in [ ]
field_pat = re.compile(r'\[(.+?)\]')
# Collect variables
scope = {}
# for re.sub
def replacement(match):
code = match.group(1)
try:
# If string can be evaluate out a value, return it.
return str(eval(code, scope))
except SyntaxError:
# else exec the assignment statement in action scope.
exec code in scope
# ...... return empty string
return ''
# Get all text in a string
# Also, there is another way, consider Chapter 11
lines = []
for line in fileinput.input():
lines.append(line)
text = ''.join(lines)
# replace all items match field pattern
print field_pat.sub(replacement, text)
另外这是 strings.txt 文件内的内容:
[x = 2]
[y = 3]
The sum of [x] and [y] is [x + y]
运行结果如下:
The sum of 2 and 3 is 5
我的疑问是:
程序的最后一行
print field_pat.sub(replacement, text)
为何只有两个参数?
根据官方对 re.sub() 的文档,re.sub() 的最少参数是3个。
官方文档
迷茫2017-04-18 09:19:31
還是文件搜尋和替換:
另一個常見任務是找到某個模式的所有符合項,並將它們替換為不同的字串。 sub() 方法接受一個替換值,可以是字串或函數,以及要處理的字串。
雷雷傳回透過將字串中最左邊不重疊的 RE 替換為替換替換而獲得的字串。如果未找到模式,則字串原樣傳回。
可選參數count是要替換的模式出現的最大次數; count 必須是非負整數。預設值 0 表示替換所有出現的情況。
高洛峰2017-04-18 09:19:31
(請搭配 @selfboot 之良方服用)
field_pat.sub(replacement, text)
並不是 re.sub()
...
是
sub(repl, string, count=0)
Identical to the sub() function, using the compiled pattern.
Python2-sub
>>> import re
>>> field_pat = re.compile(r'\[(.+?)\]')
>>> field_pat
<_sre.SRE_Pattern object at 0x7fa09b67fdd8>
>>> type(field_pat)
<type '_sre.SRE_Pattern'>
>>> field_pat.sub
<built-in method sub of _sre.SRE_Pattern object at 0x7fa09b67fdd8>
>>> help(field_pat.sub)
sub(...)
sub(repl, string[, count = 0]) --> newstring
Return the string obtained by replacing the leftmost non-overlapping
occurrences of pattern in string by the replacement repl.
regex.sub(repl, string, count=0)
Identical to the sub() function, using the compiled pattern.
Python3 - regex.sub
>>> import re
>>> field_pat = re.compile(r'\[(.+?)\]')
>>> field_pat
re.compile(r'\[(.+?)\]', re.UNICODE)
>>> type(field_pat)
_sre.SRE_Pattern
>>> field_pat.sub
<function SRE_Pattern.sub>
>>> help(field_pat.sub)
sub(...) method of _sre.SRE_Pattern instance
sub(repl, string[, count = 0]) -> newstring.
Return the string obtained by replacing the leftmost non-overlapping
occurrences of pattern in string by the replacement repl.
我回答過的問題: Python-QA