Updated May 2019.
In one of my CS courses, we had to code our own interpreter for a given language specification. After the lectures on BNF, lexers, and parsers, I decided to get some practice with a personal project.
I decided to write a simple, proof-of-concept unit converter in Python, which would be able to convert between different metric units, and even U.S. customary units. The unit converter also performs basic arithmetic operations on numbers, converting any units as necessary.
The unit converter works by expressing each measurement by a value and a list of the seven base SI units: kg, m, s, K, A, mol, and cd.
For example, numbers would be represented by something like:
The tables used to convert between units look like this:
Notice how the customary system has a lot of units for each base SI unit, and none of the scales are at all nice to work with (all the scales are used to convert to metric equivalent bases). This table is what allows us to convert between systems and units, and perform basic arithmetic operations on them. By storing everything in base SI units, it becomes easier to add, multiply, convert, etc. between different units and systems.
To install the module for importing into other scripts, you can put the files in a directory called
unitconvert in one of these paths:
~/.local/lib/python3.6/site-packages/ /usr/local/lib/python3.6/dist-packages/ /usr/lib/python3/dist-packages/
To import it into a script:
Examples can be found here on GitHub.
unitconvert can be downloaded on GitHub.