"""General functions for string transformations."""importastfrompygaps.utilities.exceptionsimportParsingError
[docs]defconvert_chemformula_ltx(string:str)->str:""" Convert a chemical formula string to a matplotlib parsable format (latex). Parameters ---------- string or Adsorbate: str String to process. Returns ------- str Processed string. """result=getattr(string,'formula',None)ifresultisNone:result=""number_processing=Falseforiinstring:ifi.isdigit():ifnotnumber_processing:result+='_{'number_processing=Trueelse:ifnumber_processing:result+='}'number_processing=Falseresult+=iifnumber_processing:result+='}'returnf'${result}$'
[docs]defconvert_unit_ltx(string:str,negative:bool=False)->str:""" Convert a unit string to a nice matplotlib parsable format (latex). Parameters ---------- string: str String to process. negative: bool Whether the power is negative instead. Returns ------- str Processed string. """result=""number_processing=Falseforiinstring:ifi.isdigit():ifnotnumber_processing:result+='^{'ifnegative:result+='-'negative=Falsenumber_processing=Trueelse:ifnumber_processing:result+='}'number_processing=Falseifi=="(":result+='_{'continueifi==")":result+='}'continueresult+=(i)ifnumber_processing:result+='}'ifnegative:result+='^{-1}'returnresult
def_is_none(s:str)->bool:"""Check if a value is a text None."""ifnots:returnTrueifs.lower()=='none':returnTruereturnFalsedef_is_float(s:str)->bool:"""Check if a value is a float."""try:float(s)returnTrueexceptValueError:returnFalsedef_is_bool(s:str)->bool:"""Check a value is a text bool."""ifs.lower()in['true','false']:returnTruereturnFalsedef_from_bool(s:str)->bool:"""Convert a string into a boolean."""ifs.lower()=='true':returnTrueifs.lower()=='false':returnFalseraiseValueError('String cannot be converted to bool')def_is_list(s:str)->bool:"""Check a value is a simple list."""ifs.startswith('[')ands.endswith(']'):returnTruereturnFalsedef_from_list(s:str):"""Convert a value into a list/tuple/dict."""# note that the function will fail if the list has other spacesreturnast.literal_eval(s.replace(' ',","))def_to_string(s):"""Convert a value into a CSV-safe string."""ifisinstance(s,list):return'['+' '.join([str(x)forxins])+"]"ifisinstance(s,tuple):return'('+' '.join([str(x)forxins])+")"returnstr(s)
[docs]defcast_string(s):"""Check and cast strings of various data types."""if_is_none(s):returnNoneif_is_bool(s):return_from_bool(s)ifs.isnumeric():returnint(s)if_is_float(s):returnfloat(s)if_is_list(s):return_from_list(s)ifisinstance(s,str):returnsraiseParsingError(f"Could not parse value '{s}'")