當前位置: 首頁>>代碼示例>>Python>>正文


Python markdown.markdown方法代碼示例

本文整理匯總了Python中markdown.markdown方法的典型用法代碼示例。如果您正苦於以下問題:Python markdown.markdown方法的具體用法?Python markdown.markdown怎麽用?Python markdown.markdown使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在markdown的用法示例。


在下文中一共展示了markdown.markdown方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: GetReadMe

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def GetReadMe(path):
    # README
    ext='Markdown'
    readme,_,i=has_item(path,'README.md')
    if readme==False:
        readme,_,i=has_item(path,'readme.md')
    if readme==False:
        ext='Text'
        readme,_,i=has_item(path,'readme.txt')
    if readme==False:
        ext='Text'
        readme,_,i=has_item(path,'README.txt')
    if readme!=False:
        readme=markdown.markdown(readme, extensions=['tables','codehilite'])
    return readme,ext


# @cache.memoize(timeout=60*5) 
開發者ID:abbeyokgo,項目名稱:PyOne,代碼行數:20,代碼來源:common.py

示例2: test_inline_tag_content

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def test_inline_tag_content(self):
		"""content of inline-type tags should be converted"""
		emptyElements = self.emptyElements
		for tag in html2markdown._inlineTags:
			if tag in emptyElements:
				continue

			testStr = '<%s style="text-decoration:line-through;">strike <strong>through</strong> some text</%s> here' % (tag, tag)
			expectedStr = '<%s style="text-decoration:line-through;">strike __through__ some text</%s> here' % (tag, tag)

			mdStr = html2markdown.convert(testStr)

			self.assertEqual(mdStr, expectedStr, 'Tag: {}'.format(tag))

			bs = bs4.BeautifulSoup(markdown.markdown(mdStr), 'html.parser')
			self.assertEqual(
				len(bs.find_all('strong')), 1 if tag != 'strong' else 2,
				'Tag: {}. Conversion: {}'.format(tag, mdStr)
			) 
開發者ID:dlon,項目名稱:html2markdown,代碼行數:21,代碼來源:tests.py

示例3: serve_document

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def serve_document(filebase):
    if "\\" in filebase or "/" in filebase or "." in filebase:
        return Response(status=404)

    try:
        with open("docs/{}.md".format(filebase), "r") as f:
            html = markdown.markdown(f.read(), output_format="html5")
    except IOError:
        return Response(status=404)

    for open_tag, title, close_tag in re.findall("<(h[0-9])>(.*?)</(h[0-9])>", html):
        if open_tag != close_tag:
            continue

        chunk = "<{tag}>{contents}</{tag}>".format(tag=open_tag, contents=title)
        section_id = title.replace(" ", "-").lower()
        new_chunk = '<{tag} id="{id}">{contents}</{tag}>'.format(tag=open_tag, id=section_id, contents=title)
        html = html.replace(chunk, new_chunk)

    html = '<div class="documentation container">{}</div'.format(html)
    return Response(html, 200) 
開發者ID:mitre,項目名稱:cascade-server,代碼行數:23,代碼來源:docs.py

示例4: spotPatch

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def spotPatch(self, soup):

		# Replace <pre> tags on wattpad.
		# wp_div = soup.find_all('div', class_="panel-reading")
		# for item in wp_div:
		# Fukkit, just nuke them in general
		for pre in soup.find_all("pre"):
			pre.name = "div"
			contentstr = pre.encode_contents().decode("utf-8")

			formatted = markdown.markdown(contentstr, extensions=["mdx_linkify"])
			formatted = WebRequest.as_soup(formatted)
			if formatted.find("html"):
				formatted.html.unwrap()
				formatted.body.unwrap()
				pre.replace_with(formatted)
			# print(pre)
		return soup 
開發者ID:fake-name,項目名稱:ReadableWebProxy,代碼行數:20,代碼來源:GarbageInlineProcessors.py

示例5: register_extensions

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def register_extensions(app):
    """
    Register Flask extensions.
    """
    cache.init_app(app)
    db.init_app(app)
    csrf_protect.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    ma.init_app(app)
    json_api.init_app(app)
    migrate.init_app(app, db)

    @app.context_processor
    def inject_debug():
        """
        Make the debug variable available to templates.
        """
        return dict(debug=app.debug, version=version)

    @app.template_filter()
    def safe_markdown(text):
        return jinja2.Markup(markdown.markdown(text))

    return None 
開發者ID:ewels,項目名稱:MegaQC,代碼行數:27,代碼來源:app.py

示例6: registerExtensions

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def registerExtensions(self, extensions, configs):
        """
        Register extensions with this instance of Markdown.

        Keyword arguments:

        * extensions: A list of extensions, which can either
           be strings or objects.  See the docstring on Markdown.
        * configs: A dictionary mapping module names to config options.

        """
        for ext in extensions:
            if isinstance(ext, str):
                ext = self.build_extension(ext, configs.get(ext, []))
            if isinstance(ext, Extension):
                # might raise NotImplementedError, but that's the extension author's problem
                ext.extendMarkdown(self, globals())
            elif ext is not None:
                raise ValueError('Extension "%s.%s" must be of type: "markdown.Extension".' \
                    % (ext.__class__.__module__, ext.__class__.__name__))

        return self 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:24,代碼來源:__init__.py

示例7: markdown

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def markdown(text, *args, **kwargs):
    """Convert a markdown string to HTML and return HTML as a unicode string.

    This is a shortcut function for `Markdown` class to cover the most
    basic use case.  It initializes an instance of Markdown, loads the
    necessary extensions and runs the parser on the given text.

    Keyword arguments:

    * text: Markdown formatted text as Unicode or ASCII string.
    * Any arguments accepted by the Markdown class.

    Returns: An HTML document as a string.

    """
    md = Markdown(*args, **kwargs)
    return md.convert(text) 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:19,代碼來源:__init__.py

示例8: run

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def run(self, lines):
        '''
        Find and remove all Abbreviation references from the text.
        Each reference is set as a new AbbrPattern in the markdown instance.
        
        '''
        new_text = []
        for line in lines:
            m = ABBR_REF_RE.match(line)
            if m:
                abbr = m.group('abbr').strip()
                title = m.group('title').strip()
                self.markdown.inlinePatterns['abbr-%s'%abbr] = \
                    AbbrPattern(self._generate_pattern(abbr), title)
            else:
                new_text.append(line)
        return new_text 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:19,代碼來源:abbr.py

示例9: markdown_and_sanitize

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def markdown_and_sanitize(markdown_string):
  """Takes a markdown string and converts it into sanitized html.

  It uses the table extension; while that's not a part of standard
  markdown, it is sure to be useful for TensorBoard users.

  The sanitizer uses the allowed_tags and attributes specified above. Mostly,
  we ensure that our standard use cases like tables and links are supported.

  Args:
    markdown_string: Markdown string to sanitize

  Returns:
    a string containing sanitized html for input markdown
  """
  # Convert to utf-8 whenever we have a binary input.
  if isinstance(markdown_string, six.binary_type):
    markdown_string = markdown_string.decode('utf-8')

  string_html = markdown.markdown(
      markdown_string, extensions=['markdown.extensions.tables'])
  string_sanitized = bleach.clean(
      string_html, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES)
  return string_sanitized 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:26,代碼來源:text_plugin.py

示例10: __init__

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def __init__(self, markdown_file: Path):

        super().__init__()

        self.markdown_file = markdown_file

        self.html = bleach.clean(
            markdown.markdown(
                get_path(self.markdown_file).read_text(),
                extensions=[
                    "tables",
                    "sane_lists",
                    _WebvizMarkdownExtension(base_path=markdown_file.parent),
                ],
            ),
            tags=Markdown.ALLOWED_TAGS,
            attributes=Markdown.ALLOWED_ATTRIBUTES,
            styles=Markdown.ALLOWED_STYLES,
        )

        # Workaround for upstream issue https://github.com/plotly/dash-core-components/issues/746,
        # where we convert void html tags from <tag> to <tag/>.
        self.html = re.sub("<img (.*?[^/])>", r"<img \1/>", self.html)
        self.html = self.html.replace("<br>", "<br/>").replace("<hr>", "<hr/>") 
開發者ID:equinor,項目名稱:webviz-config,代碼行數:26,代碼來源:_markdown.py

示例11: markdown

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def markdown(text, *args, **kwargs):
    """Convert a Markdown string to HTML and return HTML as a Unicode string.

    This is a shortcut function for `Markdown` class to cover the most
    basic use case.  It initializes an instance of Markdown, loads the
    necessary extensions and runs the parser on the given text.

    Keyword arguments:

    * text: Markdown formatted text as Unicode or ASCII string.
    * Any arguments accepted by the Markdown class.

    Returns: An HTML document as a string.

    """
    md = Markdown(*args, **kwargs)
    return md.convert(text) 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:19,代碼來源:__init__.py

示例12: markdown_extract

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def markdown_extract(text, extract_length=190):
    ''' return the plain text representation of markdown encoded text.  That
    is the texted without any html tags.  If extract_length is 0 then it
    will not be truncated.'''
    if not text:
        return ''
    plain = RE_MD_HTML_TAGS.sub('', markdown(text))
    if not extract_length or len(plain) < extract_length:
        return literal(plain)

    return literal(
        unicode(
            whtext.truncate(
                plain,
                length=extract_length,
                indicator='...',
                whole_word=True
            )
        )
    ) 
開發者ID:italia,項目名稱:daf-recipes,代碼行數:22,代碼來源:helpers.py

示例13: render_markdown

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def render_markdown(data, auto_link=True, allow_html=False):
    ''' Returns the data as rendered markdown

    :param auto_link: Should ckan specific links be created e.g. `group:xxx`
    :type auto_link: bool
    :param allow_html: If True then html entities in the markdown data.
        This is dangerous if users have added malicious content.
        If False all html tags are removed.
    :type allow_html: bool
    '''
    if not data:
        return ''
    if allow_html:
        data = markdown(data.strip())
    else:
        data = RE_MD_HTML_TAGS.sub('', data.strip())
        data = clean_html(
            markdown(data), strip=True,
            tags=MARKDOWN_TAGS, attributes=MARKDOWN_ATTRIBUTES)
    # tags can be added by tag:... or tag:"...." and a link will be made
    # from it
    if auto_link:
        data = html_auto_link(data)
    return literal(data) 
開發者ID:italia,項目名稱:daf-recipes,代碼行數:26,代碼來源:helpers.py

示例14: render

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def render(text, truncate_words=None):
    html = markdown.markdown(
        text,
        extensions=[
            EmojiExtension(emoji_index=twemoji),
            SuperFencesCodeExtension(),
            MagiclinkExtension(),
            DeleteSubExtension(subscript=False),
            Nl2BrExtension(),
        ]
    )
    markdown_attrs['img'].append('class')
    markdown_tags.append('pre')
    clean_html = bleach.clean(html, markdown_tags, markdown_attrs)

    if truncate_words:
        clean_html = Truncator(clean_html).words(num=truncate_words, html=True)

    return clean_html 
開發者ID:yunity,項目名稱:karrot-backend,代碼行數:21,代碼來源:markdown.py

示例15: md2html

# 需要導入模塊: import markdown [as 別名]
# 或者: from markdown import markdown [as 別名]
def md2html(text):
    text = str(text)
    import textwrap
    res = Markup(markdown.markdown(
        textwrap.dedent(text),
        [
            'markdown.extensions.codehilite',
            'markdown.extensions.nl2br',
            'markdown.extensions.extra',
            'markdown.extensions.admonition'
        ], extension_configs={
            'markdown.extensions.codehilite': {
                'noclasses': True,
                'pygments_style': 'colorful'
            }
        }))
    return res 
開發者ID:JosXa,項目名稱:BotListBot,代碼行數:19,代碼來源:botlistapi.py


注:本文中的markdown.markdown方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。