我有一个 python 函数f(foo: string) -> string
。我不写该函数的详细信息,因为它可能会发生变化。
我需要得到all来自 Markdown 文件的链接并将其替换为该函数的结果。
示例:此链接
This is a text and this [is first link](http://example.com "Example Title") and
this [is a second](#example) link.
将替换为
This is a text and this [is first link](result1 "Example Title") and
this [is a second](result2) link.
where f(http://example.com)=result1
and f(#example)=result2
。那是result1
的输出是f(http://example.com)
and result2
的输出是f(#example)
.
我们可以用 python 正则表达式或某些具有 markdown 文件特征的特定包来执行此操作吗?
修改姆赖因哈特 https://stackoverflow.com/a/30738268/2755116回答这个问题,可以这样做:
def find_md_links(md):
"""Returns dict of links in markdown:
'regular': [foo](some.url)
'footnotes': [foo][3]
[3]: some.url
"""
# https://stackoverflow.com/a/30738268/2755116
INLINE_LINK_RE = re.compile(r'\[([^\]]+)\]\(([^)]+)\)')
FOOTNOTE_LINK_TEXT_RE = re.compile(r'\[([^\]]+)\]\[(\d+)\]')
FOOTNOTE_LINK_URL_RE = re.compile(r'\[(\d+)\]:\s+(\S+)')
links = list(INLINE_LINK_RE.findall(md))
footnote_links = dict(FOOTNOTE_LINK_TEXT_RE.findall(md))
footnote_urls = dict(FOOTNOTE_LINK_URL_RE.findall(md))
footnotes_linking = []
for key in footnote_links.keys():
footnotes_linking.append((footnote_links[key], footnote_urls[footnote_links[key]]))
return {'regular': links, 'footnotes': footnotes_linking}
def replace_md_links(md, f):
"""Replace links url to f(url)"""
links = find_md_links(md)
newmd = md
for r in links['regular']:
newmd = newmd.replace(r[1], f(r[1]))
for r in links['footnotes']:
newmd = newmd.replace(r[1], f(r[1]))
return newmd
f
是一个函数。例如,我使用此函数仅更改属于以下位置的链接#
in replace_md_links
def mychange(s, prefix="/static/entrades/", suffix=".md.html"):
"""Change links from tiddlywiki syntax [foo](#something) to [foo](prefix + something + suffix)"""
if s.startswith('#'):
return prefix + slugify.slugify(urllib.parse.unquote( s.replace('#', '', 1) )) + suffix
else:
return s
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)