【问题标题】:How to remove leading and trailing whitespace from each line in an MD file while preserving empty lines?如何在保留空行的同时从 MD 文件中的每一行中删除前导和尾随空格?
【发布时间】:2021-11-19 10:41:57
【问题描述】:

我将 Markdown 文本存储在一个变量中,稍后我将其写入 MD 文件。 Markdown 包含尾随和前导空格以及只有空格的行。我试图从变量以及MD 文件中删除空格,但无济于事。

请注意:

  • 标题 ## 包含前导空格
  • 第 [1] 段包含前导空格
  • 段落 [2] 之后的第二行不为空,但包含两个空格(可能在代码块中不可见)
  • 段落 [a.] 后跟两个空格
markdown = ''' ## This is a headline

 [1] This is the first paragraph

[2] This is the second paragraph

  
a. This is the third paragraph;  
b. This is the fourth paragraph.'''

with open("output.md", "w") as f_out:
    f_out.write(markdown)

理想情况下,output.md 应该是这样的:

## This is a headline

[1] This is the first paragraph

[2] This is the second paragraph

a. This is the third paragraph;
b. This is the fourth paragraph.

编辑:将@Mortz 接受的答案应用于真实来源,我意识到 Markdown 为 <br> 标签使用了两个空格。因此在这种情况下不需要删除尾随空格。可以使用以下命令删除前导空格:clean_markdown = '\n'.join(_.lstrip() for _ in markdown.split('\n'))

【问题讨论】:

    标签: python markdown


    【解决方案1】:

    您可以拆分换行符 - '\n' 并重新加入所有条目,去掉前导和尾随空格 -

    print(repr(markdown))
    #' ## This is a headline\n\n [1] This is the first paragraph\n \n [2] This is the second paragraph\n \n   \n   a. This is the third paragraph;  \n   b. This is the fourth paragraph.'
    
    clean_markdown = '\n'.join(_.strip() for _ in markdown.split('\n'))
    
    print(repr(clean_markdown))
    #'## This is a headline\n\n[1] This is the first paragraph\n\n[2] This is the second paragraph\n\n\na. This is the third paragraph;\nb. This is the fourth paragraph.'
    

    然后将此clean_markdown 写入您的文件

    【讨论】:

    • 感谢您抽出宝贵时间回答;这将删除所有尾随和前导空格并回答问题的主要部分。是否也可以在此解决方案中实现删除双空行?或者,一旦文件被写出,我将处理它(参见this thread)。
    • 抱歉,我不确定您所说的“双空行”是什么意思。您的意思是要用一个空行替换两个或多个连续的空行吗?
    • 对不起,如果我的措辞不准确。确切地说,两行或多行的空行应该恰好替换为一行。应用于示例,段落 [2] 和 [a.] 之间的两行应减少为一行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2013-06-03
    相关资源
    最近更新 更多