Source code for pcmdi_metrics.utils.string_constructor
classStringConstructor:""" This class aims at spotting keywords in a string and replacing them. """def__init__(self,template=None):""" Instantiates a StringConstructor object. """self.template=template# Generate the keys and set them to emptykeys=self.keys()forkinkeys:setattr(self,k,"")defkeys(self,template=None):iftemplateisNone:template=self.templateiftemplateisNone:return[]# Determine the keywords in the templatekeys=[]template_split=template.split("%(")[1:]iflen(template_split)>0:forkintemplate_split:sp=k.split(")")ifsp[0]notinkeys:keys.append(sp[0])returnkeysdefconstruct(self,template=None,**kw):""" Accepts a string with an unlimited number of keywords to replace. """iftemplateisNone:template=self.template# Replace the keywords with their valuesforkinself.keys():ifknotinkw:passtemplate=template.replace("%("+k+")",kw.get(k,getattr(self,k,"")))returntemplatedefreverse(self,name,debug=False):""" The reverse function attempts to take a template and derive its keyword values based on name parameter. """out={}template=self.templateforkinself.keys():sp=template.split("%%(%s)"%k)i1=name.find(sp[0])+len(sp[0])j1=sp[1].find("%(")ifj1==-1:ifsp[1]=="":val=name[i1:]else:i2=name.find(sp[1])val=name[i1:i2]else:i2=name[i1:].find(sp[1][:j1])val=name[i1:i1+i2]template=template.replace("%%(%s)"%k,val)out[k]=valifself.construct(self.template,**out)!=name:raiseValueError("Invalid pattern sent")returnoutdef__call__(self,*args,**kw):"""default call is construct function"""returnself.construct(*args,**kw)
[docs]deffill_template(template:str,**kwargs)->str:""" Fill in a template string with keyword values. Parameters ---------- - template (str): The template string containing keywords of the form '%(keyword)'. - kwargs (dict): Keyword arguments with values to replace in the template. Returns ------- - str: The filled-in string with replaced keywords. Examples -------- >>> from pcmdi_metrics.utils import fill_template >>> template = "This is a %(adjective) %(noun) that %(verb)." >>> filled_string = fill_template(template, adjective="great", noun="example", verb="works") >>> print(filled_string) # It will print "This is a great example that works." """filler=StringConstructor(template)filled_template=filler.construct(**kwargs)returnfilled_template