Esempio n. 1
0
def load_convs(filename):
    """Read conversion factors from the given file.
    
    The file format is line-based:
       from [whitespace] to [whitespace] factor
    Anything past the third element is ignored.  Lines starting with # are 
    ignored.

    """
    convs = []
    with open(filename, "r") as f:
        for line in f:
            parts = line.split()
            if line.startswith("#") or len(parts) < 3:
                continue
            convs.extend(factor_conv(tokens.parse_infix(parts[0]), tokens.parse_infix(parts[1]), parts[2]))
    return convs
Esempio n. 2
0
    path, _to = find_conversion_path(convs, frm, to)
    value = frm.value
    for conv in path:
        value = conv.func(value)
    ret = _to.copy()
    ret.value = value
    return ret


def simplify(convs, frm):
    return convert(convs, frm, None)


if __name__ == "__main__":
    print "pynuts conversion demo"
    convs = load_convs("data.txt")

    #    print convert(convs, tokens.parse_infix('2 W h'), tokens.parse_infix('J'))

    print "Simplify 2 mol/L * N_A:"

    jph = tokens.parse_infix("2 mol/L * N_A")
    target = simplify(convs, jph)
    print convert(convs, jph, target)

    print "Convert 3 ha to km^2"
    print convert(convs, tokens.parse_infix("3 ha"), tokens.parse_infix("km^2"))

    print "Convert 5 furlongs per fortnight to meter per hour"
    print convert(convs, tokens.parse_infix("5 fur/ftn"), tokens.parse_infix("m/h"))