• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python six.text_type函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中matplotlib.externals.six.text_type函数的典型用法代码示例。如果您正苦于以下问题:Python text_type函数的具体用法?Python text_type怎么用?Python text_type使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了text_type函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: _write_svgfonts

    def _write_svgfonts(self):
        if not rcParams['svg.fonttype'] == 'svgfont':
            return

        writer = self.writer
        writer.start('defs')
        for font_fname, chars in six.iteritems(self._fonts):
            font = get_font(font_fname)
            font.set_size(72, 72)
            sfnt = font.get_sfnt()
            writer.start('font', id=sfnt[(1, 0, 0, 4)])
            writer.element(
                'font-face',
                attrib={
                    'font-family': font.family_name,
                    'font-style': font.style_name.lower(),
                    'units-per-em': '72',
                    'bbox': ' '.join(six.text_type(x / 64.0) for x in font.bbox)})
            for char in chars:
                glyph = font.load_char(char, flags=LOAD_NO_HINTING)
                verts, codes = font.get_path()
                path = Path(verts, codes)
                path_data = self._convert_path(path)
                # name = font.get_glyph_name(char)
                writer.element(
                    'glyph',
                    d=path_data,
                    attrib={
                        # 'glyph-name': name,
                        'unicode': unichr(char),
                        'horiz-adv-x': six.text_type(glyph.linearHoriAdvance / 65536.0)})
            writer.end('font')
        writer.end('defs')
开发者ID:Tillsten,项目名称:matplotlib,代码行数:33,代码来源:backend_svg.py


示例2: draw_path_collection

    def draw_path_collection(self, gc, master_transform, paths, all_transforms,
                             offsets, offsetTrans, facecolors, edgecolors,
                             linewidths, linestyles, antialiaseds, urls,
                             offset_position):
        # Is the optimization worth it? Rough calculation:
        # cost of emitting a path in-line is
        #    (len_path + 5) * uses_per_path
        # cost of definition+use is
        #    (len_path + 3) + 9 * uses_per_path
        len_path = len(paths[0].vertices) if len(paths) > 0 else 0
        uses_per_path = self._iter_collection_uses_per_path(
            paths, all_transforms, offsets, facecolors, edgecolors)
        should_do_optimization = \
            len_path + 9 * uses_per_path + 3 < (len_path + 5) * uses_per_path
        if not should_do_optimization:
            return RendererBase.draw_path_collection(
                self, gc, master_transform, paths, all_transforms,
                offsets, offsetTrans, facecolors, edgecolors,
                linewidths, linestyles, antialiaseds, urls,
                offset_position)

        writer = self.writer
        path_codes = []
        writer.start('defs')
        for i, (path, transform) in enumerate(self._iter_collection_raw_paths(
            master_transform, paths, all_transforms)):
            transform = Affine2D(transform.get_matrix()).scale(1.0, -1.0)
            d = self._convert_path(path, transform, simplify=False)
            oid = 'C%x_%x_%s' % (self._path_collection_id, i,
                                  self._make_id('', d))
            writer.element('path', id=oid, d=d)
            path_codes.append(oid)
        writer.end('defs')

        for xo, yo, path_id, gc0, rgbFace in self._iter_collection(
            gc, master_transform, all_transforms, path_codes, offsets,
            offsetTrans, facecolors, edgecolors, linewidths, linestyles,
            antialiaseds, urls, offset_position):
            clipid = self._get_clip(gc0)
            url = gc0.get_url()
            if url is not None:
                writer.start('a', attrib={'xlink:href': url})
            if clipid is not None:
                writer.start('g', attrib={'clip-path': 'url(#%s)' % clipid})
            attrib = {
                'xlink:href': '#%s' % path_id,
                'x': six.text_type(xo),
                'y': six.text_type(self.height - yo),
                'style': self._get_style(gc0, rgbFace)
                }
            writer.element('use', attrib=attrib)
            if clipid is not None:
                writer.end('g')
            if url is not None:
                writer.end('a')

        self._path_collection_id += 1
开发者ID:Tillsten,项目名称:matplotlib,代码行数:57,代码来源:backend_svg.py


示例3: validate_stringlist

def validate_stringlist(s):
    'return a list'
    if isinstance(s, six.string_types):
        return [six.text_type(v.strip()) for v in s.split(',') if v.strip()]
    elif type(s) in (list, tuple):
        return [six.text_type(v) for v in s if v]
    else:
        msg = "'s' must be of type [ string | list | tuple ]"
        raise ValueError(msg)
开发者ID:joferkington,项目名称:matplotlib,代码行数:9,代码来源:rcsetup.py


示例4: set_family

 def set_family(self, family):
     """
     Change the font family.  May be either an alias (generic name
     is CSS parlance), such as: 'serif', 'sans-serif', 'cursive',
     'fantasy', or 'monospace', a real font name or a list of real
     font names.  Real font names are not supported when
     `text.usetex` is `True`.
     """
     if family is None:
         family = rcParams['font.family']
     if is_string_like(family):
         family = [six.text_type(family)]
     elif (not is_string_like(family) and isinstance(family, Iterable)):
         family = [six.text_type(f) for f in family]
     self._family = family
开发者ID:NishantMF,项目名称:matplotlib,代码行数:15,代码来源:font_manager.py


示例5: draw_text

    def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
        # Note: x,y are device/display coords, not user-coords, unlike other
        # draw_* methods
        if _debug: print('%s.%s()' % (self.__class__.__name__, _fn_name()))

        if ismath:
            self._draw_mathtext(gc, x, y, s, prop, angle)

        else:
            ctx = gc.ctx
            ctx.new_path()
            ctx.move_to (x, y)
            ctx.select_font_face (prop.get_name(),
                                  self.fontangles [prop.get_style()],
                                  self.fontweights[prop.get_weight()])

            size = prop.get_size_in_points() * self.dpi / 72.0

            ctx.save()
            if angle:
                ctx.rotate (-angle * np.pi / 180)
            ctx.set_font_size (size)

            if HAS_CAIRO_CFFI:
                if not isinstance(s, six.text_type):
                    s = six.text_type(s)
            else:
                if not six.PY3 and isinstance(s, six.text_type):
                    s = s.encode("utf-8")

            ctx.show_text(s)
            ctx.restore()
开发者ID:717524640,项目名称:matplotlib,代码行数:32,代码来源:backend_cairo.py


示例6: edit_parameters

        def edit_parameters(self):
            allaxes = self.canvas.figure.get_axes()
            if len(allaxes) == 1:
                axes = allaxes[0]
            else:
                titles = []
                for axes in allaxes:
                    title = axes.get_title()
                    ylabel = axes.get_ylabel()
                    label = axes.get_label()
                    if title:
                        fmt = "%(title)s"
                        if ylabel:
                            fmt += ": %(ylabel)s"
                        fmt += " (%(axes_repr)s)"
                    elif ylabel:
                        fmt = "%(axes_repr)s (%(ylabel)s)"
                    elif label:
                        fmt = "%(axes_repr)s (%(label)s)"
                    else:
                        fmt = "%(axes_repr)s"
                    titles.append(fmt % dict(title=title,
                                         ylabel=ylabel, label=label,
                                         axes_repr=repr(axes)))
                item, ok = QtWidgets.QInputDialog.getItem(
                    self.parent, 'Customize', 'Select axes:', titles, 0, False)
                if ok:
                    axes = allaxes[titles.index(six.text_type(item))]
                else:
                    return

            figureoptions.figure_edit(axes, self)
开发者ID:giltis,项目名称:matplotlib,代码行数:32,代码来源:backend_qt5.py


示例7: update_savefig_format

def update_savefig_format(value):
    # The old savefig.extension could also have a value of "auto", but
    # the new savefig.format does not.  We need to fix this here.
    value = six.text_type(value)
    if value == 'auto':
        value = 'png'
    return value
开发者ID:pwgerman,项目名称:matplotlib,代码行数:7,代码来源:rcsetup.py


示例8: get_fontconfig_fonts

def get_fontconfig_fonts(fontext='ttf'):
    """
    Grab a list of all the fonts that are being tracked by fontconfig
    by making a system call to ``fc-list``.  This is an easy way to
    grab all of the fonts the user wants to be made available to
    applications, without needing knowing where all of them reside.
    """
    fontext = get_fontext_synonyms(fontext)

    fontfiles = {}
    try:
        pipe = subprocess.Popen(['fc-list', '--format=%{file}\\n'],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        output = pipe.communicate()[0]
    except (OSError, IOError):
        # Calling fc-list did not work, so we'll just return nothing
        return fontfiles

    if pipe.returncode == 0:
        # The line breaks between results are in ascii, but each entry
        # is in in sys.filesystemencoding().
        for fname in output.split(b'\n'):
            try:
                fname = six.text_type(fname, sys.getfilesystemencoding())
            except UnicodeDecodeError:
                continue
            if (os.path.splitext(fname)[1][1:] in fontext and
                os.path.exists(fname)):
                fontfiles[fname] = 1

    return fontfiles
开发者ID:NishantMF,项目名称:matplotlib,代码行数:32,代码来源:font_manager.py


示例9: get_text_width_height_descent

 def get_text_width_height_descent(self, s, prop, ismath):
     if ismath=='TeX':
         # todo: handle props
         texmanager = self.get_texmanager()
         fontsize = prop.get_size_in_points()
         w, h, d = texmanager.get_text_width_height_descent(s, fontsize,
                                                            renderer=self)
         return w, h, d
     if ismath:
         ox, oy, width, height, descent, fonts, used_characters = \
             self.mathtext_parser.parse(s, self.dpi, prop)
         return width, height, descent
     family =  prop.get_family()
     weight = prop.get_weight()
     # transform weight into string for the native backend
     if weight >= 700:
         weight = 'bold'
     else:
         weight = 'normal'
     style = prop.get_style()
     points = prop.get_size_in_points()
     size = self.points_to_pixels(points)
     width, height, descent = self.gc.get_text_width_height_descent(
         six.text_type(s), family, size, weight, style)
     return  width, height, descent
开发者ID:ethanhelfman,项目名称:InstaGet,代码行数:25,代码来源:backend_macosx.py


示例10: get

 def get(self):
     valuelist = []
     for index, (label, value) in enumerate(self.data):
         field = self.widgets[index]
         if label is None:
             # Separator / Comment
             continue
         elif tuple_to_qfont(value) is not None:
             value = field.get_font()
         elif isinstance(value, six.string_types) or is_color_like(value):
             value = six.text_type(field.text())
         elif isinstance(value, (list, tuple)):
             index = int(field.currentIndex())
             if isinstance(value[0], (list, tuple)):
                 value = value[index][0]
             else:
                 value = value[index]
         elif isinstance(value, bool):
             value = field.checkState() == QtCore.Qt.Checked
         elif isinstance(value, float):
             value = float(str(field.text()))
         elif isinstance(value, int):
             value = int(field.value())
         elif isinstance(value, datetime.datetime):
             value = field.dateTime().toPyDateTime()
         elif isinstance(value, datetime.date):
             value = field.date().toPyDate()
         else:
             value = eval(str(field.text()))
         valuelist.append(value)
     return valuelist
开发者ID:ChenchenYo,项目名称:matplotlib,代码行数:31,代码来源:formlayout.py


示例11: edit_parameters

        def edit_parameters(self):
            allaxes = self.canvas.figure.get_axes()
            if not allaxes:
                QtWidgets.QMessageBox.warning(
                    self.parent, "Error", "There are no axes to edit.")
                return
            if len(allaxes) == 1:
                axes = allaxes[0]
            else:
                titles = []
                for axes in allaxes:
                    name = (axes.get_title() or
                            " - ".join(filter(None, [axes.get_xlabel(),
                                                     axes.get_ylabel()])) or
                            "<anonymous {} (id: {:#x})>".format(
                                type(axes).__name__, id(axes)))
                    titles.append(name)
                item, ok = QtWidgets.QInputDialog.getItem(
                    self.parent, 'Customize', 'Select axes:', titles, 0, False)
                if ok:
                    axes = allaxes[titles.index(six.text_type(item))]
                else:
                    return

            figureoptions.figure_edit(axes, self)
开发者ID:phametus,项目名称:matplotlib,代码行数:25,代码来源:backend_qt5.py


示例12: __init__

    def __init__(self):

        if self.texcache is None:
            raise RuntimeError(
                ('Cannot create TexManager, as there is no cache directory '
                 'available'))

        mkdirs(self.texcache)
        ff = rcParams['font.family']
        if len(ff) == 1 and ff[0].lower() in self.font_families:
            self.font_family = ff[0].lower()
        elif isinstance(ff, six.string_types) and ff.lower() in self.font_families:
            self.font_family = ff.lower()
        else:
            mpl.verbose.report(
                'font.family must be one of (%s) when text.usetex is True. '
                'serif will be used by default.' %
                   ', '.join(self.font_families),
                'helpful')
            self.font_family = 'serif'

        fontconfig = [self.font_family]
        for font_family, font_family_attr in [(ff, ff.replace('-', '_'))
                                              for ff in self.font_families]:
            for font in rcParams['font.' + font_family]:
                if font.lower() in self.font_info:
                    setattr(self, font_family_attr,
                            self.font_info[font.lower()])
                    if DEBUG:
                        print('family: %s, font: %s, info: %s' %
                              (font_family, font,
                               self.font_info[font.lower()]))
                    break
                else:
                    if DEBUG:
                        print('$s font is not compatible with usetex')
            else:
                mpl.verbose.report('No LaTeX-compatible font found for the '
                                   '%s font family in rcParams. Using '
                                   'default.' % ff, 'helpful')
                setattr(self, font_family_attr, self.font_info[font_family])
            fontconfig.append(getattr(self, font_family_attr)[0])
        # Add a hash of the latex preamble to self._fontconfig so that the
        # correct png is selected for strings rendered with same font and dpi
        # even if the latex preamble changes within the session
        preamble_bytes = six.text_type(self.get_custom_preamble()).encode('utf-8')
        fontconfig.append(md5(preamble_bytes).hexdigest())
        self._fontconfig = ''.join(fontconfig)

        # The following packages and commands need to be included in the latex
        # file's preamble:
        cmd = [self.serif[1], self.sans_serif[1], self.monospace[1]]
        if self.font_family == 'cursive':
            cmd.append(self.cursive[1])
        while '\\usepackage{type1cm}' in cmd:
            cmd.remove('\\usepackage{type1cm}')
        cmd = '\n'.join(cmd)
        self._font_preamble = '\n'.join(['\\usepackage{type1cm}', cmd,
                                         '\\usepackage{textcomp}'])
开发者ID:Allen-smith,项目名称:ctf-tools,代码行数:59,代码来源:texmanager.py


示例13: get_basefile

 def get_basefile(self, tex, fontsize, dpi=None):
     """
     returns a filename based on a hash of the string, fontsize, and dpi
     """
     s = "".join([tex, self.get_font_config(), "%f" % fontsize, self.get_custom_preamble(), str(dpi or "")])
     # make sure hash is consistent for all strings, regardless of encoding:
     bytes = six.text_type(s).encode("utf-8")
     return os.path.join(self.texcache, md5(bytes).hexdigest())
开发者ID:KevKeating,项目名称:matplotlib,代码行数:8,代码来源:texmanager.py


示例14: validate_string_or_None

def validate_string_or_None(s):
    """convert s to string or raise"""
    if s is None:
        return None
    try:
        return six.text_type(s)
    except ValueError:
        raise ValueError('Could not convert "%s" to string' % s)
开发者ID:KyleBsingh,项目名称:matplotlib,代码行数:8,代码来源:rcsetup.py


示例15: _write_clips

 def _write_clips(self):
     if not len(self._clipd):
         return
     writer = self.writer
     writer.start('defs')
     for clip, oid in six.itervalues(self._clipd):
         writer.start('clipPath', id=oid)
         if len(clip) == 2:
             clippath, clippath_trans = clip
             path_data = self._convert_path(clippath, clippath_trans, simplify=False)
             writer.element('path', d=path_data)
         else:
             x, y, w, h = clip
             writer.element('rect', x=six.text_type(x), y=six.text_type(y),
                            width=six.text_type(w), height=six.text_type(h))
         writer.end('clipPath')
     writer.end('defs')
开发者ID:Tillsten,项目名称:matplotlib,代码行数:17,代码来源:backend_svg.py


示例16: draw_markers

    def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
        if not len(path.vertices):
            return

        writer = self.writer
        path_data = self._convert_path(
            marker_path,
            marker_trans + Affine2D().scale(1.0, -1.0),
            simplify=False)
        style = self._get_style_dict(gc, rgbFace)
        dictkey = (path_data, generate_css(style))
        oid = self._markers.get(dictkey)
        for key in list(six.iterkeys(style)):
            if not key.startswith('stroke'):
                del style[key]
        style = generate_css(style)

        if oid is None:
            oid = self._make_id('m', dictkey)
            writer.start('defs')
            writer.element('path', id=oid, d=path_data, style=style)
            writer.end('defs')
            self._markers[dictkey] = oid

        attrib = {}
        clipid = self._get_clip(gc)
        if clipid is not None:
            attrib['clip-path'] = 'url(#%s)' % clipid
        writer.start('g', attrib=attrib)

        trans_and_flip = self._make_flip_transform(trans)
        attrib = {'xlink:href': '#%s' % oid}
        clip = (0, 0, self.width*72, self.height*72)
        for vertices, code in path.iter_segments(
                trans_and_flip, clip=clip, simplify=False):
            if len(vertices):
                x, y = vertices[-2:]
                attrib['x'] = six.text_type(x)
                attrib['y'] = six.text_type(y)
                attrib['style'] = self._get_style(gc, rgbFace)
                writer.element('use', attrib=attrib)
        writer.end('g')
开发者ID:Tillsten,项目名称:matplotlib,代码行数:42,代码来源:backend_svg.py


示例17: _print_bitmap

 def _print_bitmap(self, filename, *args, **kwargs):
     # In backend_bases.py, print_figure changes the dpi of the figure.
     # But since we are essentially redrawing the picture, we need the
     # original dpi. Pick it up from the renderer.
     dpi = kwargs['dpi']
     old_dpi = self.figure.dpi
     self.figure.dpi = self.renderer.dpi
     width, height = self.figure.get_size_inches()
     width, height = width*dpi, height*dpi
     filename = six.text_type(filename)
     self.write_bitmap(filename, width, height, dpi)
     self.figure.dpi = old_dpi
开发者ID:ethanhelfman,项目名称:InstaGet,代码行数:12,代码来源:backend_macosx.py


示例18: __init__

    def __init__(self):

        if self.texcache is None:
            raise RuntimeError(("Cannot create TexManager, as there is no cache directory " "available"))

        mkdirs(self.texcache)
        ff = rcParams["font.family"]
        if len(ff) == 1 and ff[0].lower() in self.font_families:
            self.font_family = ff[0].lower()
        elif isinstance(ff, six.string_types) and ff.lower() in self.font_families:
            self.font_family = ff.lower()
        else:
            mpl.verbose.report(
                "font.family must be one of (%s) when text.usetex is True. "
                "serif will be used by default." % ", ".join(self.font_families),
                "helpful",
            )
            self.font_family = "serif"

        fontconfig = [self.font_family]
        for font_family, font_family_attr in [(ff, ff.replace("-", "_")) for ff in self.font_families]:
            for font in rcParams["font." + font_family]:
                if font.lower() in self.font_info:
                    setattr(self, font_family_attr, self.font_info[font.lower()])
                    if DEBUG:
                        print("family: %s, font: %s, info: %s" % (font_family, font, self.font_info[font.lower()]))
                    break
                else:
                    if DEBUG:
                        print("$s font is not compatible with usetex")
            else:
                mpl.verbose.report(
                    "No LaTeX-compatible font found for the " "%s font family in rcParams. Using " "default." % ff,
                    "helpful",
                )
                setattr(self, font_family_attr, self.font_info[font_family])
            fontconfig.append(getattr(self, font_family_attr)[0])
        # Add a hash of the latex preamble to self._fontconfig so that the
        # correct png is selected for strings rendered with same font and dpi
        # even if the latex preamble changes within the session
        preamble_bytes = six.text_type(self.get_custom_preamble()).encode("utf-8")
        fontconfig.append(md5(preamble_bytes).hexdigest())
        self._fontconfig = "".join(fontconfig)

        # The following packages and commands need to be included in the latex
        # file's preamble:
        cmd = [self.serif[1], self.sans_serif[1], self.monospace[1]]
        if self.font_family == "cursive":
            cmd.append(self.cursive[1])
        while "\\usepackage{type1cm}" in cmd:
            cmd.remove("\\usepackage{type1cm}")
        cmd = "\n".join(cmd)
        self._font_preamble = "\n".join(["\\usepackage{type1cm}", cmd, "\\usepackage{textcomp}"])
开发者ID:KevKeating,项目名称:matplotlib,代码行数:53,代码来源:texmanager.py


示例19: _write_hatches

 def _write_hatches(self):
     if not len(self._hatchd):
         return
     HATCH_SIZE = 72
     writer = self.writer
     writer.start('defs')
     for ((path, face, stroke), oid) in six.itervalues(self._hatchd):
         writer.start(
             'pattern',
             id=oid,
             patternUnits="userSpaceOnUse",
             x="0", y="0", width=six.text_type(HATCH_SIZE),
             height=six.text_type(HATCH_SIZE))
         path_data = self._convert_path(
             path,
             Affine2D().scale(HATCH_SIZE).scale(1.0, -1.0).translate(0, HATCH_SIZE),
             simplify=False)
         if face is None:
             fill = 'none'
         else:
             fill = rgb2hex(face)
         writer.element(
             'rect',
             x="0", y="0", width=six.text_type(HATCH_SIZE+1),
             height=six.text_type(HATCH_SIZE+1),
             fill=fill)
         writer.element(
             'path',
             d=path_data,
             style=generate_css({
                 'fill': rgb2hex(stroke),
                 'stroke': rgb2hex(stroke),
                 'stroke-width': '1.0',
                 'stroke-linecap': 'butt',
                 'stroke-linejoin': 'miter'
                 })
             )
         writer.end('pattern')
     writer.end('defs')
开发者ID:ChenchenYo,项目名称:matplotlib,代码行数:39,代码来源:backend_svg.py


示例20: test_dviread

def test_dviread():
    dir = os.path.join(os.path.dirname(__file__), 'baseline_images', 'dviread')
    with open(os.path.join(dir, 'test.json')) as f:
        correct = json.load(f)
    with dr.Dvi(os.path.join(dir, 'test.dvi'), None) as dvi:
        data = [{'text': [[t.x, t.y,
                           six.unichr(t.glyph),
                           six.text_type(t.font.texname),
                           round(t.font.size, 2)]
                          for t in page.text],
                 'boxes': [[b.x, b.y, b.height, b.width] for b in page.boxes]}
                for page in dvi]
    assert_equal(data, correct)
开发者ID:carlrose,项目名称:matplotlib,代码行数:13,代码来源:test_dviread.py



注:本文中的matplotlib.externals.six.text_type函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python moves.xrange函数代码示例发布时间:2022-05-27
下一篇:
Python six.itervalues函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap