【问题标题】:Python script for getting sections contents from a markdown document用于从 Markdown 文档中获取部分内容的 Python 脚本
【发布时间】:2016-01-22 19:08:45
【问题描述】:

我尝试在 python 中编写一个脚本,用于在一个 Markdown 文档的各个部分中划分内容。例如,在

# Section 1

Hello

# Section 2

Bla la dsds

# Section 3 #

Ssss

## Subsection ##

aaaa

我想得到:

contents = ['# Section 1\n\nHello\n', '# Section 2\n\nBla la dsds\n', '# Section 3 #\n\nSsss\n\n## Subsection ##\n\naaaa']

我该怎么做?

【问题讨论】:

  • 提示:itertools.groupby(your_text.splitlines(), lambda line: line.startswith('# '))itertools.groupby(your_text.splitlines(), operator.methodcaller('startswith', '# '))

标签: python split markdown


【解决方案1】:
def get_sections(s):
    for sec in s.split('\n# '):
        yield sec if sec.startswith('# ') else '# '+sec

contents = """# Section 1

Hello

# Section 2

Bla la dsds

# Section 3 #

Ssss

## Subsection ##

aaaa"""

for i,sec in enumerate(get_sections(contents)):
    print(i,sec)

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案2】:

我对 Markdown 不是很了解,但我会试一试。

markdown 文件只是一个 txt 文件,所以你可以像这样加载它:

file = open('markdownfile.md','r')
data = file.read()
file.close()

看起来你想要拆分的共同因素是"\n#",但也没有遵循,而是另一个"#",或者只是没有"\n##"

所以我可以看到的一种方法是按"\n#" 拆分文件,然后修复小节:

splitData = data.split("\n#")
for i in xrange(len(splitData)-1,-1,-1):#going backwards
    if splitData[i][0] == '#':#subsection
        splitData[i-1] += '\n#'+splitData.pop(i)#being sure to add back what we remove from the .split
    else:#section
        splitData[i] = '#'+splitData[i]#adding back the wanted part removed with the .split

或者你可以遍历字符并进行手动拆分

contents = []
for i in xrange(len(data)-1-3,-1,-1):
    if data[i:i+2] == '\n#' and data[i:i+3] != '\n##'
        contents.append(data[i+1:])#append the section
        data = data[:i]#remove from data
contents.reverse()

我希望这会有所帮助。

编辑:您不能只将data"\n# " 分开(最后有空格),因为(通过我的研究)空间不必在那里,因为它是识别为节标题。 (例如#Section 1 仍然可以工作)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 2013-10-15
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2014-05-26
    相关资源
    最近更新 更多