File: unicode_format.py

package info (click to toggle)
python-astropy 1.3-8~bpo8%2B2
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 44,292 kB
  • sloc: ansic: 160,360; python: 137,322; sh: 11,493; lex: 7,638; yacc: 4,956; xml: 1,796; makefile: 474; cpp: 364
file content (71 lines) | stat: -rw-r--r-- 1,729 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst

"""
Handles the "Unicode" unit format.
"""

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

from . import console, utils


class Unicode(console.Console):
    """
    Output-only format to display pretty formatting at the console
    using Unicode characters.

    For example::

      >>> import astropy.units as u
      >>> print(u.bar.decompose().to_string('unicode'))
              kg
      100000 ────
             m s²
    """

    _times = "×"
    _line = "─"

    @classmethod
    def _get_unit_name(cls, unit):
        return unit.get_format_name('unicode')

    @classmethod
    def format_exponential_notation(cls, val):
        m, ex = utils.split_mantissa_exponent(val)

        parts = []
        if m:
            parts.append(m.replace('-', '−'))

        if ex:
            parts.append("10{0}".format(
                cls._format_superscript(ex)))

        return cls._times.join(parts)

    @classmethod
    def _format_superscript(cls, number):
        mapping = {
            '0': '⁰',
            '1': '¹',
            '2': '²',
            '3': '³',
            '4': '⁴',
            '5': '⁵',
            '6': '⁶',
            '7': '⁷',
            '8': '⁸',
            '9': '⁹',
            '-': '⁻',
            '−': '⁻',
            # This is actually a "raised omission bracket", but it's
            # the closest thing I could find to a superscript solidus.
            '/': '⸍',
            }
        output = []
        for c in number:
            output.append(mapping[c])
        return ''.join(output)