Python Code to Extract Paragraphs by Heading from Markdown
Sure! To accomplish this task, you will need to use the markdown library in Python. You can install it using the command pip install markdown. \n\nAssuming you have an article written in Markdown format, you can use the following Python code to find paragraphs based on their headings and return the text of the entire paragraph:\n\npython\nimport markdown\n\ndef find_paragraphs_by_heading(md_text, heading):\n # Convert the Markdown text to HTML\n html_text = markdown.markdown(md_text)\n \n paragraphs = []\n current_paragraph = ""\n is_target_heading = False\n \n # Split the HTML text into lines\n lines = html_text.split("\n")\n \n for line in lines:\n # Check if the line contains the target heading\n if line.startswith(f"<h{heading}>") : is_target_heading = True\n elif line.startswith("<h") and line[2] == ">": is_target_heading = False\n \n # Extract paragraphs under the target heading\n if is_target_heading and line.startswith("<p>") : current_paragraph += line[3:-4] # Remove the <p> and </p> tags\n elif current_paragraph:\n paragraphs.append(current_paragraph.strip())\n current_paragraph = ""\n \n return paragraphs\n\n# Example usage\nmarkdown_text = """\n# Heading 1\n\nParagraph 1 under heading 1.\n\nParagraph 2 under heading 1.\n\n## Heading 2\n\nParagraph 1 under heading 2.\n\n### Heading 3\n\nParagraph 1 under heading 3.\n\n## Heading 4\n\nParagraph 1 under heading 4.\n"""\n\ntarget_heading = 2\nfound_paragraphs = find_paragraphs_by_heading(markdown_text, target_heading)\n\nfor paragraph in found_paragraphs:\n print(paragraph)\n\n\nIn this example, we define the find_paragraphs_by_heading function that takes the Markdown text and the target heading level as parameters. It converts the Markdown text to HTML using the markdown.markdown function.\n\nThe function then iterates through the HTML lines, identifies the target heading, and extracts the paragraphs that follow it. It returns a list of paragraphs found under the target heading level.\n\nYou can customize the target_heading variable to specify the desired heading level (1, 2, 3, etc.). The code will extract and print all paragraphs found under that heading level.
原文地址: https://www.cveoy.top/t/topic/qc1u 著作权归作者所有。请勿转载和采集!