[Python] How to convert String with newline and tabs to nested bullets in word docx using...

Discussão em 'Python' iniciado por Stack, Fevereiro 25, 2025.

  1. Stack

    Stack Membro Participativo


    Convert a markdown LLM generated text to suitable word supported bullet/sub-bullet format.
    ​

    Currently we are trying to convert a LLM generated multibullet and subbullet text into a word bullet.

    The first level bullets are correctly convert but on subbullet / and lower subbullet the bulleting style applied manual (string square bullet or whole cirle) are not detected / treated as bulleting style by Word DOCX.

    For example:


    Input string: "title of the bullet\n\t- content 1\n\t- content 2" This string is convert to "title of the bullet\n\t▪ content 1\n\t▪ content 2"
    ​

    Following string is then added to the DOCX paragraph.

    String has to be convert to a bullet -title/paragraph, subbullet - content1, and subbullet - content 2 We tried adding additional whitespace but this didn't worked out.

    We are primarily using python-docx library.


    def check_if_nature_subbullet(self,section,bullet):
    data=bullet.get('values', {}).get('result')
    if section in ['II'] and data!=None:
    data=data.replace("\n\n-","\n\n\t○ ")
    if re.search(r"\n\s*-", data):
    data=re.sub(r'\n\s*-',"\n\t\t▪ ", data)
    return data


    def replace_text_in_paragraph(self, paragraph, old_text, new_text, bold=False, italics=False, underline=False):
    if old_text in paragraph.text:
    if "SECTION_II_" in old_text:
    print(f"{old_text} => {new_text}")
    font_name = paragraph.runs[0].font.name if paragraph.runs else 'Garamond'
    font_size = paragraph.runs[0].font.size if paragraph.runs else None


    full_text = ''.join(run.text for run in paragraph.runs)
    parts = full_text.split(old_text)
    full_text = full_text.replace(old_text, new_text)
    full_text = full_text.replace('\n\n','\n')


    for run in paragraph.runs:
    run.text = ''

    self.add_markdown_text(paragraph, full_text, font_name, font_size) #this function only applies font style.



    In the Word file, old_text is a placeholder, and new_text is the text we are replacing it with.

    The new_text contains some sample strings that are not being recognized as sub-bullets in the .docx file.

    Continue reading...

Compartilhe esta Página