本文整理汇总了Python中string.Template.find方法的典型用法代码示例。如果您正苦于以下问题:Python Template.find方法的具体用法?Python Template.find怎么用?Python Template.find使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类string.Template
的用法示例。
在下文中一共展示了Template.find方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: print
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import find [as 别名]
#保留5为小数,前面补0
print "pi = %*.*f" % (20, 10, math.pi)
#使用×替代宽度和小数位
print "pi = %+2f" % math.pi
#用+显示正负号
print "pi = %-10.2f" % math.pi
#用-表示左对齐
print ('% 5d' % 10) + '\n' + ('%5d' % -10)
#空白‘’表示在正数前增加一个空格
print "#问题:怎么在小数点s后面补零?#"
s = 'Lucy in the sky with dimond'
print s.find('sky')
#find,找到字符串中的子串位置,未找到返回-1
'''本章节的其他string method :
link.join(seq),用link连接字符串seq;
str.lower()表示转换str内的字母为小写;
str.title(),转换str内的首字母大写,建议用string.capwords(str);
seq.replace('words')查找替换seq中的words;
seq.split('symbol')以symbol为分隔符分开seq;
seq.strip('symbol')去除seq前后指定的symbol,symbol为空者去掉字符串两端的空格;
maketrans 字符替换
示例2: handler
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import find [as 别名]
#.........这里部分代码省略.........
req.write(content)
return(apache.OK)
# Convert content to UTF-8
content = content.decode("utf-8")
# Extract meta data of content
meta_data = re.search('^\s*title\.\s*(?P<title>[^\n]*)', content)
meta_data_content = { \
'title': ''
}
if not meta_data is None:
for g, r in meta_data.groupdict().iteritems():
meta_data_content[g] = r
del(meta_data)
# Remove meta data from content
content = re.sub('^\s*title\.\s+.*\n', '', content, 1)
# Replace newlines
content = re.sub('^\n*', '', content)
content = re.sub('\n', r'<br />\n', content)
# Replace lists placeholders
content = re.sub('(?ms)(^\*\s+.*?<br />)\n^<br />\n', r'<ul>\n\1\n</ul>\n', content)
content = re.sub('(?ms)(^#\s+.*?<br />)\n^<br />\n', r'<ol>\n\1\n</ol>\n', content)
content = re.sub('(?ms)^[\*#]\s+(.*?(?=\n[\*#]\s|</ul>|</ol>))', r'<li>\1</li>', content)
# Headings
content = re.sub('(?m)^h([1-6])\.\s+(.*)<br />', r'<h\1>\2</h\1>', content)
# Set response HTTP headers
req.content_type = 'text/' + output_type
# Return content with applied templates
try:
# TODO: handle directory listings?
template = repo.heads.master.commit.tree['templates/' + output_type].data_stream.read()
content = Template(template).safe_substitute( \
path=requested_object.path, \
title=meta_data_content['title'], \
body=content, \
charset=git_commit.encoding, \
commit=git_commit, \
author=git_commit.author, \
date=datetime.fromtimestamp(git_commit.committed_date)
)
except:
if config['gitblog.report_errors'] is True:
etype, evalue, etb = sys.exc_info()
req.write('An error occured on line %i while delivering content path /%s: %s' % \
(etb.tb_lineno, requested_object.path, evalue))
req.status = apache.HTTP_INTERNAL_SERVER_ERROR
return(apache.DONE)
return(apache.HTTP_INTERNAL_SERVER_ERROR)
# Replace placeholders
if content.find('{toc}'):
# TODO: insert anchors
content = re.sub(r'(?m)^{toc}', r'<u>Inhaltsverzeichnis | Table of contents</u><br />TODO', content, 1)
# Text decoration
content = re.sub(r'(?<!\\){i(?<!\\)}(.*)(?<!\\){i(?<!\\)}', r'<i>\1</i>', content)
content = re.sub(r'(?<!\\){b(?<!\\)}(.*)(?<!\\){b(?<!\\)}', r'<b>\1</b>', content)
content = re.sub(r'(?<!\\){u(?<!\\)}(.*)(?<!\\){u(?<!\\)}', r'<u>\1</u>', content)
# Code blocks
content = re.sub(r'(?ms)^{code[^}]*}<br />\n(.*?(?!{code}))<br />\n{code}<br />\n', r'<pre><code>\1</code></pre>', content)
# TODO: run over all matches
#content = re.sub(r'(?m)(<pre><code>.*(?!</code></pre>))<br />', r'\1', content)
content = re.sub(r'(?m)(?<=<pre><code>)(.*)<br />', r'\1', content)
# Text formatting
content = re.sub(r' -- ', r' – ', content)
content = re.sub(r' --- ', r' — ', content)
# Hyperlinks
content = re.sub('{a:([^}:]*)}', r'<a href="\1">\1</a>', content)
content = re.sub('{a:([^}:]*):([^}]*)}', r'<a href="\1">\2</a>', content)
# Images
content = re.sub('{img:([^:]+)}', r'<p><img src="\1"/></p>', content)
content = re.sub('{img:([^:]+):([^}]*)}', r'<p><img src="\1" alt="\2"/><br />\2</p>', content)
# Remove escapes
content = re.sub(r'\\{(i|b|u|img|a|toc)\\}', r'{\1}', content)
# Cleanup content
content = re.sub('</p><br />', '</p>', content)
#content = re.sub('<br />$|\n', '', content)
content = re.sub('<br />$', '', content)
# Return output
req.headers_out.add('Content-Length', str(len(content)))
req.write(content.encode('utf-8'))
return(apache.OK)
示例3: selectGenericFiles
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import find [as 别名]
def selectGenericFiles(urls, **kwargs):
"""
Allow to describe a ``generic`` file organization : the list of files returned
by this function is composed of files which :
- match the patterns in ``url`` once these patterns are instantiated by
the values in kwargs, and
- contain the ``variable`` provided in kwargs
- match the `period`` provided in kwargs
In the pattern strings, no keyword is mandatory
Example :
>>> selectGenericFiles(project='my_projet',model='my_model', simulation='lastexp', variable='tas', period='1980', urls=['~/DATA/${project}/${model}/*${variable}*YYYY*.nc)']
/home/stephane/DATA/my_project/my_model/somefilewith_tas_Y1980.nc
In the pattern strings, the keywords that can be used in addition to the argument
names (e.g. ${model}) are:
- ${variable} : use it if the files are split by variable and
filenames do include the variable name, as this speed up the search
- YYYY, YYYYMM, YYYYMMDD : use it for indicating the start date of
the period covered by each file, if this is applicable in the
file naming; use a second time for end date, if applicable
(otherwise the assumption is that the whole year -resp. month or
day- is included in the file
- wildcards '?' and '*' for matching respectively one and any number of characters
"""
rep=[]
period=kwargs['period']
if type(period) is str : period=init_period(period)
variable=kwargs['variable']
mustHaveVariable=False
if "filenameVar" in kwargs and kwargs['filenameVar'] :
kwargs['variable']=kwargs['filenameVar']
mustHaveVariable=True
for l in urls :
template=Template(l)
# There is no use to look for files which path is not specific
# to the required variable when we know it should
if l.find("${variable}") < 0 and mustHaveVariable :
continue
#
# Instantiate keywords in pattern with attributes values
template=template.safe_substitute(**kwargs)
#print "template after attributes replace : "+template
#
# Construct a pattern for globbing dates
temp2=template
dt=dict(YYYY="????",YYYYMM="??????",YYYYMMDD="????????")
for k in dt : temp2=temp2.replace(k,dt[k])
clogger.debug("Globbing on : "+temp2)
lfiles=glob.glob(temp2)
#
# Analyze all filenames
for f in lfiles :
# print "looking at file"+f
# Construct regexp for extracting dates from filename
dt=dict(YYYY="([0-9]{4})",YYYYMM="([0-9]{6})",
YYYYMMDD="([0-9]{10})")
regexp=None
# print "template before searching dates : "+template
lkeys=dt.keys() ; lkeys.sort(reverse=True)
for key in lkeys :
# print "searchin "+key+" in "+template
start=template.find(key)
if (start>=0 ) :
# print "found "+key
regexp=template.replace(key,dt[key],1)
hasEnd=False
start=regexp.find(key)
if (start >=0 ) :
hasEnd=True
regexp=regexp.replace(key,dt[key],1)
break
#
# Analyze file time period
fperiod=None
if regexp :
regexp=regexp.replace("*",".*").replace("?",r".")
# print "regexp for extracting dates : "+regexp
start=re.sub(regexp,r'\1',f)
if hasEnd :
end=re.sub(regexp,r'\2',f)
fperiod=init_period("%s-%s"%(start,end))
else :
fperiod=init_period(start)
#
# Filter file time period against required period
else :
if ( 'frequency' in kwargs and kwargs['frequency']=="fx") :
if (l.find("${variable}")>=0) or fileHasVar(f,variable) :
clogger.debug("adding fixed field :"+f)
#.........这里部分代码省略.........
示例4: selectGenericFiles
# 需要导入模块: from string import Template [as 别名]
# 或者: from string.Template import find [as 别名]
def selectGenericFiles(urls, **kwargs):
"""
Allow to describe a ``generic`` file organization : the list of files returned
by this function is composed of files which :
- match the patterns in ``url`` once these patterns are instantiated by
the values in kwargs, and
- contain the ``variable`` provided in kwargs
- match the `period`` provided in kwargs
In the pattern strings, no keyword is mandatory
Example :
>>> selectGenericFiles(project='my_projet',model='my_model', simulation='lastexp', variable='tas', period='1980', urls=['~/DATA/${project}/${model}/*${variable}*YYYY*.nc)']
/home/stephane/DATA/my_project/my_model/somefilewith_tas_Y1980.nc
In the pattern strings, the keywords that can be used in addition to the argument
names (e.g. ${model}) are:
- ${variable} : use it if the files are split by variable and
filenames do include the variable name, as this speed up the search
- YYYY, YYYYMM, YYYYMMDD : use it for indicating the start date of
the period covered by each file, if this is applicable in the
file naming; use a second time for end date, if applicable
(otherwise the assumption is that the whole year -resp. month or
day- is included in the file
- wildcards '?' and '*' for matching respectively one and any number of characters
"""
rep=[]
period=kwargs['period']
if type(period) is str : period=init_period(period)
variable=kwargs['variable']
altvar=kwargs.get('filenameVar',variable)
# a dict and an ordered list of date globbing patterns
dt=dict(YYYY="????",YYYYMM="??????",YYYYMMDD="????????")
lkeys=dt.keys() ; lkeys.sort(reverse=True)
# a dict and an ordered list for matching dates
dr=dict(YYYY="([0-9]{4})",YYYYMM="([0-9]{6})", YYYYMMDD="([0-9]{8})")
rkeys=dr.keys() ; rkeys.sort(reverse=True)
#
for l in urls :
# Instantiate keywords in pattern with attributes values
template=Template(l).safe_substitute(**kwargs)
#print "template after attributes replace : "+template
#
# Construct a pattern for globbing dates
temp2=template ;
for k in lkeys : temp2=temp2.replace(k,dt[k])
lfiles=glob.glob(temp2)
clogger.debug("Globbing %d files for varname on %s : "%(len(lfiles),temp2))
#
# If unsuccessful using varname, try with filenameVar
if len(lfiles)==0 and "filenameVar" in kwargs and kwargs['filenameVar'] :
kwargs['variable']=kwargs['filenameVar']
template=Template(l).safe_substitute(**kwargs)
temp2=template
for k in lkeys : temp2=temp2.replace(k,dt[k])
#
lfiles=glob.glob(temp2)
clogger.debug("Globbing %d files for filenamevar on %s: "%(len(lfiles),temp2))
# Construct regexp for extracting dates from filename
regexp=None
#print "template before searching dates : "+template
for key in rkeys :
#print "searchin "+key+" in "+=Template(l)
start=template.find(key)
if (start>=0 ) :
#print "found "+key
regexp=template.replace(key,dr[key],1)
hasEnd=False
start=regexp.find(key)
if (start >=0 ) :
hasEnd=True
regexp=regexp.replace(key,dr[key],1)
break
#print "regexp before searching dates : "+regexp
#
for f in lfiles :
#print "processing file "+f
#
# Analyze file time period
fperiod=None
if regexp :
regexp0=regexp.replace("*",".*").replace("?",r".")
#print "regexp for extracting dates : "+regexp
start=re.sub(regexp0,r'\1',f)
if start==f:
raise Climaf_Data_Error("Start period not found") #? LV
if hasEnd :
end=re.sub(regexp0,r'\2',f)
fperiod=init_period("%s-%s"%(start,end))
else :
#.........这里部分代码省略.........