2016-01-22 49 views
-1

我尝试在python中编写脚本,以便在一个降价文档中的节内划分内容。例如,在用于从降价文档中获取节内容的Python脚本

# 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'] 

我怎么能这样做?

+0

提示:'itertools.groupby(your_text.splitlines(),lambda行:line.startswith('#'))'或'itertools.groupby(your_text.splitlines(),运算符。 methodcaller('startswith','#'))' – GingerPlusPlus

回答

0

我对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仍然有效)