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

Python lexers.guess_lexer_for_filename函数代码示例

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

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



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

示例1: highlight_code

def highlight_code(path, src, div=False, **kwargs):
    src = decode_charset_to_unicode(src)
    try:
        if path.endswith(('.html', '.mako')):
            lexer = MakoHtmlLexer(encoding='utf-8')
        elif path.endswith('.ptl'):
            lexer = PythonLexer(encoding='utf-8')
        elif path.endswith('.md'):
            lexer = RstLexer(encoding='utf-8')
        else:
            if path.endswith(IGNORE_FILE_EXTS):
                src = 'Hmm.., this is binary file.'
            lexer = guess_lexer_for_filename(path, src)
        lexer.encoding = 'utf-8'
        lexer.stripnl = False
    except ClassNotFound:
        # no code highlight
        lexer = TextLexer(encoding='utf-8')
    if div:
        formatter = _CodeHtmlFormatter
    else:
        formatter = HtmlFormatter

    src = highlight(src, lexer, formatter(linenos=True,
                                          lineanchors='L',
                                          anchorlinenos=True,
                                          encoding='utf-8',
                                          **kwargs))
    return src
开发者ID:dm04806,项目名称:mikoto,代码行数:29,代码来源:text.py


示例2: _detect_lang_name

 def _detect_lang_name(self, subject, paste_content):
   lexer = None
   if '.' in subject:
     if subject[-1] == ')':
       if ' (' in subject:
         name = subject.split(' (')[0]
       elif '(' in subject:
         name = subject.split('(')[0]
       else:
         name = subject
     else:
       name = subject
     if name.split('.')[-1] in self.recognized_extenstions:
       try:
         lexer = guess_lexer_for_filename(name, paste_content, encoding='utf-8')
       except (ClassNotFound, ImportError):
         pass
   if lexer is None and len(paste_content) >= 20:
     try:
       lexer = guess_lexer(paste_content, encoding='utf-8')
     except (ClassNotFound, ImportError):
       pass
   if lexer is None:
     try:
       lexer = get_lexer_by_name('text', encoding='utf-8')
     except (ClassNotFound, ImportError) as e:
       self.log(self.logger.WARNING, '%s: %s' % (subject, e))
       return ''
   return lexer.aliases[0]
开发者ID:4cdn,项目名称:equanimous-octo-garbanzo,代码行数:29,代码来源:paste.py


示例3: show_submission_source_view

def show_submission_source_view(request, contest_id, submission_id):
    submission = get_submission_or_404(request, contest_id, submission_id, ProgramSubmission)
    raw_source = submission.source_file.read()
    raw_source, decode_error = decode_str(raw_source)
    filename = submission.source_file.file.name
    is_source_safe = False
    try:
        lexer = guess_lexer_for_filename(filename, raw_source)
        formatter = HtmlFormatter(linenos=True, line_number_chars=3, cssclass="syntax-highlight")
        formatted_source = highlight(raw_source, lexer, formatter)
        formatted_source_css = HtmlFormatter().get_style_defs(".syntax-highlight")
        is_source_safe = True
    except ClassNotFound:
        formatted_source = raw_source
        formatted_source_css = ""
    download_url = reverse(
        "download_submission_source", kwargs={"contest_id": request.contest.id, "submission_id": submission_id}
    )
    return TemplateResponse(
        request,
        "programs/source.html",
        {
            "source": formatted_source,
            "css": formatted_source_css,
            "is_source_safe": is_source_safe,
            "download_url": download_url,
            "decode_error": decode_error,
        },
    )
开发者ID:neeraj9,项目名称:oioioi,代码行数:29,代码来源:views.py


示例4: _generate_preview_html

    def _generate_preview_html(self, data):
        """Return the first few truncated lines of the text file."""
        from reviewboard.diffviewer.chunk_generator import \
            NoWrapperHtmlFormatter

        charset = self.mimetype[2].get('charset', 'ascii')
        try:
            text = data.decode(charset)
        except UnicodeDecodeError:
            logging.error('Could not decode text file attachment %s using '
                          'charset "%s"',
                          self.attachment.pk, charset)
            text = data.decode('utf-8', 'replace')

        try:
            lexer = guess_lexer_for_filename(self.attachment.filename, text)
        except ClassNotFound:
            lexer = TextLexer()

        lines = highlight(text, lexer, NoWrapperHtmlFormatter()).splitlines()

        return ''.join([
            '<pre>%s</pre>' % line
            for line in lines[:self.TEXT_CROP_NUM_HEIGHT]
        ])
开发者ID:Anastasiya2307,项目名称:reviewboard,代码行数:25,代码来源:mimetypes.py


示例5: get_highlighted_code

def get_highlighted_code(name, code, type="terminal"):
    """
    If pygments are available on the system
    then returned output is colored. Otherwise
    unchanged content is returned.
    """
    import logging

    try:
        import pygments

        pygments
    except ImportError:
        return code
    from pygments import highlight
    from pygments.lexers import guess_lexer_for_filename, ClassNotFound
    from pygments.formatters import TerminalFormatter

    try:
        lexer = guess_lexer_for_filename(name, code)
        formatter = TerminalFormatter()
        content = highlight(code, lexer, formatter)
    except ClassNotFound:
        logging.debug("Couldn't guess Lexer, will not use pygments.")
        content = code
    return content
开发者ID:jeffjirsa,项目名称:rhodecode,代码行数:26,代码来源:helpers.py


示例6: process

def process(context):
    """Main routine for metrics."""
    metrics = {}

    # import all the needed metric modules
    metric_modules = __import_metric_modules(context['include_metrics'])

    # instantiate all the desired metric classes
    metric_instance = __instantiate_metric(metric_modules, context)

    cm = ComputeMetrics(metric_instance, context)

    # main loop
    for i, in_file in enumerate(context['in_file_names']):
        # print 'file %i: %s' % (i, in_file)
        try:
            cm.reset()
            fin = open(os.path.join(context['base'], in_file), 'r')
            code = ''.join(fin.readlines())
            fin.close()
            # define lexographical scanner to use for this run
            try:
                lex = guess_lexer_for_filename(in_file, code, encoding='guess')
                # encoding is 'guess', chardet', 'utf-8'
            except:
                pass
            else:
                token_list = lex.get_tokens(code) # parse code

                metrics[in_file] = {}
                metrics[in_file].update(cm(token_list))
                metrics[in_file]['language'] = lex.name # provide language

        except IOError, e:
            sys.stderr.writelines(str(e) + " -- Skipping input file.\n\n")
开发者ID:icook,项目名称:metrics,代码行数:35,代码来源:metrics.py


示例7: show_submission_source_view_unsafe

def show_submission_source_view_unsafe(request, submission_id, source_file,
                                       download_url):
    raw_source, decode_error = decode_str(source_file.read())
    filename = source_file.file.name
    is_source_safe = False
    try:
        lexer = guess_lexer_for_filename(
            filename,
            raw_source
        )
        formatter = HtmlFormatter(linenos=True, line_number_chars=3,
                            cssclass='syntax-highlight')
        formatted_source = highlight(raw_source, lexer, formatter)
        formatted_source_css = HtmlFormatter() \
                .get_style_defs('.syntax-highlight')
        is_source_safe = True
    except ClassNotFound:
        formatted_source = raw_source
        formatted_source_css = ''

    return TemplateResponse(request, 'programs/source.html', {
        'source': formatted_source,
        'css': formatted_source_css,
        'is_source_safe': is_source_safe,
        'download_url': download_url,
        'decode_error': decode_error,
        'submission_id': submission_id
    })
开发者ID:papedaniel,项目名称:oioioi,代码行数:28,代码来源:views.py


示例8: get_highlighted

 def get_highlighted(self, filename, hl_lines=None):
     """Get the highlighted version of a file."""
     hl_lines = sorted(hl_lines or [])
     st = os.stat(filename)
     key = '%s-%d-%s-%s' % (filename, int(st.st_mtime),
                            CACHE_SERIAL, hl_lines)
     key = os.path.join(self.cache_dir,
                        hashlib.sha1(key).hexdigest() + '.html.gz')
     try:
         with gzip.open(key) as keyfile:
             return keyfile.read()
     except IOError:
         with open(filename) as infile:
             file_data = infile.read()
         try:
             lexer = lexers.guess_lexer_for_filename(filename, file_data)
         except pygments.util.ClassNotFound:
             try:
                 lexer = lexers.guess_lexer(file_data)
             except pygments.util.ClassNotFound:
                 lexer = lexers.TextLexer()
         highlight = pygments.highlight(
             file_data, lexer, formatters.HtmlFormatter(
                 hl_lines=hl_lines, linenos='table', lineanchors='line',
                 anchorlinenos=True))
         with gzip.open(key, 'w') as keyfile:
             keyfile.write(highlight.encode('utf-8'))
         return highlight
开发者ID:eklitzke,项目名称:index,代码行数:28,代码来源:file_handlers.py


示例9: programas

def programas(request, arquivo):
    erros = False
    codigo = ''
    nome = 'Erro!'

    caminho = os.path.join(programas_dir, arquivo)

    if os.path.isfile(caminho):
        try:
            with open(caminho) as programa:
                texto = programa.read().decode('utf-8')
        except IOError:
            erros = True
        else:
            nome = os.path.basename(arquivo)

            #Se não conseguir adivinhar a linguagem do programa exibe texto
            try:
                lexer = guess_lexer_for_filename(arquivo, texto)
            except ValueError:
                try:
                    lexer = guess_lexer(texto)
                except ValueError:
                    lexer = TextLexer

            # linenos pode ser inline, table, True ou ''
            # replace corrige problema com {% spaceless %}
            codigo = highlight(texto, lexer, HtmlFormatter(linenos=False)).replace('\n', '<br>\n')
    else:
        erros = True

    return render_to_response('programas.html',
            {'erros': erros, 'nome': nome, 'codigo': codigo},
            context_instance=RequestContext(request))
开发者ID:agnaldoneto,项目名称:juliobs,代码行数:34,代码来源:views.py


示例10: _highlight_syntax

    def _highlight_syntax(self):
        """If we have pygments, syntax highlight the file."""
        if self.syntax_format:
            stringified_text = \
                ''.join(str(s.decode("utf-8")) for s in self.read_lines())

            if self.syntax_format is not True:
                lexer = get_lexer_by_name(self.syntax_format)

            elif self.file_name:
                try:
                    lexer = \
                        guess_lexer_for_filename(
                            self.file_name, stringified_text)
                except TypeError:
                    # XXX pygments py3 incompatibility workaround; fixed in tip
                    lexer = guess_lexer(stringified_text)
            else:
                lexer = guess_lexer(stringified_text)

            highlighted_text = \
                highlight(
                    stringified_text, lexer,
                    TerminalFormatter(bg="dark")).split('\n')

            line_num = 1
            try:
                for line in highlighted_text:
                    self._lines[
                        self._find_line_index(line_num)].update_highlight(line)
                    line_num += 1
            except KeyError:
                # our conversions to strings sometimes adds a trailing line
                pass
开发者ID:DerekMarshall,项目名称:py-ex,代码行数:34,代码来源:ex_buffer.py


示例11: show_submission_source_view

def show_submission_source_view(request, contest_id, submission_id):
    submission = get_object_or_404(ProgramSubmission, id=submission_id)
    if contest_id != submission.problem_instance.contest_id:
        raise Http404
    check_submission_access(request, submission)
    raw_source = submission.source_file.read()
    filename = submission.source_file.file.name
    is_source_safe = True
    try:
        lexer = guess_lexer_for_filename(
            filename,
            raw_source
        )
        formatter = HtmlFormatter(linenos=True, cssclass='syntax-highlight')
        formatted_source = highlight(raw_source, lexer, formatter)
        formatted_source_css = HtmlFormatter().get_style_defs('.syntax-highlight')
    except ClassNotFound:
        formatted_source = raw_source
        formatted_source_css = ''
        is_source_safe = False
    return TemplateResponse(request, 'programs/source.html', {
        'source': formatted_source,
        'css': formatted_source_css,
        'is_source_safe': is_source_safe
    })
开发者ID:mahrud,项目名称:oioioi,代码行数:25,代码来源:views.py


示例12: __init__

 def __init__(self, parent, lexer=None, filename="a.txt"):
     super(GenericHighlighter, self).__init__(parent=parent, lexer=lexer)
     self._document = self.document()
     self._formatter = HtmlFormatter()
     self._lexer = guess_lexer_for_filename(filename, "")
     print(self._lexer)
     self.set_style('default')
开发者ID:VirtualPlants,项目名称:openalea,代码行数:7,代码来源:highlight.py


示例13: get_lexer_for_filename

def get_lexer_for_filename(filename, text="", **options):
    """Gets a lexer from a filename (usually via the filename extension).
    This mimics the behavior of ``pygments.lexers.get_lexer_for_filename()``
    and ``pygments.lexers.guess_lexer_for_filename()``.
    """
    if CACHE is None:
        load_or_build()
    exts = CACHE["lexers"]["exts"]
    fname = os.path.basename(filename)
    key = fname if fname in exts else os.path.splitext(fname)[1]
    if key in exts:
        modname, clsname = exts[key]
        mod = importlib.import_module(modname)
        cls = getattr(mod, clsname)
        lexer = cls(**options)
    else:
        # couldn't find lexer in cache, fallback to the hard way
        import inspect
        from pygments.lexers import guess_lexer_for_filename

        lexer = guess_lexer_for_filename(filename, text, **options)
        # add this filename to the cache for future use
        cls = type(lexer)
        mod = inspect.getmodule(cls)
        exts[fname] = (mod.__name__, cls.__name__)
        write_cache(cache_filename())
    return lexer
开发者ID:donnemartin,项目名称:gitsome,代码行数:27,代码来源:pygments_cache.py


示例14: to_html

	def to_html(self):
		"""Convert file document to html"""
		source_dir = get_source_directory()
		css_path = source_dir + "printing.css"

		fin = open(self.path, 'r')
		code = fin.read()

		#cmd = "source-highlight -n --style-css-file {0} --tab 2 -f html -i {1}".format(css_path, self.path)
		#p = Popen(cmd.split(), shell=False, stdout=PIPE)

		file_path_name = os.path.relpath(self.path, get_current_directory())		
		html_string = """<h1>File: {0}</h1>
		<h3>Created By: {1}, Date: {2}</h3>
		""".format(file_path_name,
					self.username,
					str(self.modifytime))

		lexer = guess_lexer_for_filename('test.py', code, stripall=True)
		
		linenos = False
		if self.args.linenumbers == True:
			linenos = 'inline'

		formatter = HtmlFormatter(style='bw', linenos=linenos)
		html_string += highlight(code, lexer, formatter)
		
		fin.close()
		return html_string
开发者ID:kellpossible,项目名称:Source2PDF,代码行数:29,代码来源:Source2Pdf.py


示例15: handleMatch

  def handleMatch(self, match):
    params = match.group('params') or ''
    rel_include_path = match.group('path')
    source_dir = os.path.dirname(self.source_path)
    include_path = os.path.join(source_dir, rel_include_path)
    try:
      with open(include_path) as include_file:
        file_text = include_file.read()
    except IOError as e:
      raise IOError('Markdown file {0} tried to include file {1}, got '
                    '{2}'.format(self.source_path,
                                 rel_include_path,
                                 e.strerror))
    include_text = choose_include_text(file_text, params, self.source_path)
    if not include_text:
      raise TaskError('Markdown file {0} tried to include file {1} but '
                      'filtered out everything'.format(self.source_path,
                                                       rel_include_path))
    el = markdown.util.etree.Element('div')
    el.set('class', 'md-included-snippet')
    try:
      lexer = guess_lexer_for_filename(include_path, file_text)
    except ClassNotFound:
      # e.g., ClassNotFound: no lexer for filename u'BUILD' found
      if 'BUILD' in include_path:
        lexer = PythonLexer()
      else:
        lexer = TextLexer()  # the boring plain-text lexer

    html_snippet = highlight(include_text,
                             lexer,
                             HtmlFormatter(cssclass='codehilite'))
    el.text = html_snippet
    return el
开发者ID:megaserg,项目名称:pants,代码行数:34,代码来源:markdown_to_html.py


示例16: _blob_detail

def _blob_detail(request, project, branch_name, git_object, path_list, branches):
    """Render a blob. Pretty prints using Pygments"""
    breadcrumbs = generate_breadcrumbs(path_list)
    
    file_name = path_list[-1]['name']
    try:
        lexer = guess_lexer_for_filename(file_name, git_object.as_raw_string())
    except:
        lexer = guess_lexer(git_object.as_raw_string())
    formatter = HtmlFormatter(linenos=True)
    pretty_printed_file = highlight(git_object.as_raw_string(), lexer, formatter)
    
    return render_to_response('project/blob.html', {
        'project': project,
        'branch_name': branch_name,
        'object': git_object,
        'path': path_list,
        'breadcrumbs': breadcrumbs,
        'pretty_print': pretty_printed_file,
        'branches': branches,
    }, context_instance=RequestContext(request))
    
    
    
    
    
开发者ID:wiremine,项目名称:cannonball,代码行数:21,代码来源:views.py


示例17: render_highlight_code

def render_highlight_code(text, path, **kwargs):
    try:
        if path.endswith(('.html', '.mako')):
            lexer = MakoHtmlLexer(encoding='utf-8')
        elif path.endswith('.ptl'):
            lexer = PythonLexer(encoding='utf-8')
        elif path.endswith('.md'):
            lexer = RstLexer(encoding='utf-8')
        else:
            if path.endswith(IGNORE_FILE_EXTS):
                text = 'Hmm.., this is binary file.'
            lexer = guess_lexer_for_filename(path, text)
        lexer.encoding = 'utf-8'
        lexer.stripnl = False
    except ClassNotFound:
        # no code highlight
        lexer = TextLexer(encoding='utf-8')

    formatter = CodeHtmlFormatter

    return highlight(text, lexer, formatter(linenos='inline',
                                            lineanchors='L',
                                            anchorlinenos=True,
                                            encoding='utf-8',
                                            **kwargs))
开发者ID:qingfeng,项目名称:mikoto,代码行数:25,代码来源:code.py


示例18: __init__

 def __init__(self, name, main_display, tabsize, multiline_window=1500,
              number_of_windows=1):
     self.name = name
     self.file = f = open(name)
     try:
         lexer = guess_lexer_for_filename(name, f.readline())
     except TypeError:
         try:
             lexer = get_lexer_by_name(os.path.splitext(name)[1][1:])
         except pygments.util.ClassNotFound:
             lexer = TextLexer()
     except pygments.util.ClassNotFound:
         lexer = TextLexer()
     lexer = Python3Lexer() if isinstance(lexer, PythonLexer) else lexer
     lexer.add_filter(NonEmptyFilter())
     lexer.add_filter('tokenmerge')
     f.seek(0)
     self.lines = []
     self.focus = 0
     self.clipboard = None
     self.clipboard_pos = None
     self.lexer = lexer
     self.w_pos = {}
     self.all_tokens = None
     self._etext = lambda w: w.edit_text
     self.multiline_window = multiline_window
     self.number_of_windows = number_of_windows
     self.main_display = main_display
     self.line_kwargs = dict(caption="", allow_tab=True, lexer=lexer,
                             wrap='clip', main_display=main_display,
                             smart_home=True, tabsize=tabsize)
开发者ID:WisdomWolf,项目名称:xo,代码行数:31,代码来源:xo.py


示例19: show

def show(name):
    name = name.replace("..", "", -1).replace(" ", " ", -1)
    file_path = os.path.join("./f", name)
    if not (os.path.exists(file_path) or os.path.isfile(file_path)):
        abort(404, u"不存在这个文件哈")

    content = open(file_path).read().decode("utf8")

    if name.endswith(".md") or name.endswith(".markdown"):
        html = misaka.html(content, extensions=\
                misaka.EXT_AUTOLINK|misaka.EXT_LAX_HTML_BLOCKS|misaka.EXT_SPACE_HEADERS|\
                misaka.EXT_SUPERSCRIPT|misaka.EXT_FENCED_CODE|misaka.EXT_NO_INTRA_EMPHASIS|\
                misaka.EXT_STRIKETHROUGH|misaka.EXT_TABLES)
        def _r(m):
            try:
                lexer_name = m.group(1)
                code = m.group(2)
                lexer = get_lexer_by_name(lexer_name)
                code = HTMLParser.HTMLParser().unescape(code)
                return highlight(code, lexer, HtmlFormatter())
            except pygments.util.ClassNotFound:
                return m.group()

        p = re.compile(r'''<pre><code class="([0-9a-zA-Z._-]+)">(.+?)</code></pre>''', re.DOTALL)
        html = p.sub(lambda m: _r(m), html)

    else:
        try:
            lexer = guess_lexer_for_filename(file_path, content)
        except pygments.util.ClassNotFound:
            lexer = get_lexer_by_name("python")
        html = highlight(content, lexer,  HtmlFormatter())

    return render_template("gfm.html", **locals())
开发者ID:MistShi,项目名称:the-gist,代码行数:34,代码来源:test.py


示例20: text_content

    def text_content(self):
        if self.size <= MAX_TEXTFILE_SIZE and not self.is_image:
            possible_markdown = self.extension in (MARKDOWN_FILE_EXTENSIONS + TEXTILE_FILE_EXTENSIONS)
            fake_extension = self.extension if not possible_markdown else u'txt'
            fake_filename = u'.'.join((self.filename, fake_extension,))

            style = styles.get_style_by_name('friendly')
            formatter = formatters.HtmlFormatter(style=style)
            style = formatter.get_style_defs()

            f = urlopen(self.file_obj.cdn_url)
            data = f.read()
            f.close()

            try:
                data = data.decode('utf-8')
                lexer = lexers.guess_lexer_for_filename(fake_filename, data)
            except (ClassNotFound, UnicodeDecodeError):
                return None

            if isinstance(lexer, lexers.TextLexer) and possible_markdown:
                format_string = u'<div class="%s">%s</div>'

                if self.extension in MARKDOWN_FILE_EXTENSIONS:
                    data = format_string % ('markdown', markdown(data))

                if self.extension in TEXTILE_FILE_EXTENSIONS:
                    data = format_string % ('textile', textile(data))

            else:
                data = u'<style>%s</style>\n%s' % (style, highlight(data, lexer, formatter))

            return data
开发者ID:zeroasterisk,项目名称:ushare,代码行数:33,代码来源:models.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python lexers.PythonLexer类代码示例发布时间:2022-05-25
下一篇:
Python lexers.guess_lexer函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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