Skip to content

gulp

parse_value(string, with_units=False)

parse a value from a GULP output file to its appropriate type e.g. int, float, str etc. Will handle units with a space.

Parameters

string: str the string containing the value to parse

bool, optional

return a tuple including uncertainty if a numeric type is expected

Returns

value the value coerced into the appropriate type

parse_value("2.3 kj/mol", with_units=True) (2.3, 'kj/mol') parse_value("5 kgm^2", with_units=True) (5, 'kgm^2') parse_value("string help") 'string help' parse_value("3.1415") * 4 12.566

Source code in chmpy/fmt/gulp.py
def parse_value(string, with_units=False):
    """parse a value from a GULP output file to its appropriate type
    e.g. int, float, str etc. Will handle units with a space.

    Parameters
    ----------
    string: str
        the string containing the value to parse

    with_uncertainty: bool, optional
        return a tuple including uncertainty if a numeric type is expected

    Returns
    -------
    value
        the value coerced into the appropriate type

    >>> parse_value("2.3 kj/mol", with_units=True)
    (2.3, 'kj/mol')
    >>> parse_value("5 kgm^2", with_units=True)
    (5, 'kgm^2')
    >>> parse_value("string help")
    'string help'
    >>> parse_value("3.1415") * 4
    12.566
    """
    match = NUMBER_REGEX.match(string)
    try:
        if match and match:
            groups = match.groups()
            number = groups[0]
            number = float(number)
            if number.is_integer():
                number = int(number)
            if with_units and len(groups) > 1:
                return number, groups[1]
            return number
        else:
            s = string.strip()
            return s
    except Exception as e:
        print(e)
    return string