Question: Repeat 'apply formatting' function to style paragraphs of text

  • Hello, everyone!

    Working on a project that will hopefully involve typesetting a printed book using Drawbot, some experience of python but probably a novice by most standards.

    Does anyone have a good suggestion of how to repeat a formatting find/replace function to identify all instances of a word within a longer text that could be italicised/colour changed for example. This would have to work for multiple words/phrases.

    I have managed to find this great example below from @gferreira but cant work out how to repeat something like this to identify and change multiple instances? Any help would be much appreciated,

    txt = '''Some title here
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla tempus justo in finibus condimentum. Proin vitae mauris ac nibh elementum consectetur. Aenean justo mi, cursus vel placerat vitae, gravida in mi.
    def applyFormatting(formattedString, findText, styleDict):
        start = str(formattedString).find(findText)
        end = start + len(findText)
        before = formattedString[:start]
        after  = formattedString[end:]
        replaceText = formattedString.copy()
        replaceText.append(findText, **styleDict)
        return before + replaceText + after
    T = FormattedString(txt, fontSize=36, font="Arial")
    T = applyFormatting(T, 'Some title here', dict(fontSize=72, font='Times New Roman', paragraphBottomSpacing=20))
    T = applyFormatting(T, 'sit amet', dict(font='Arial Bold', fill=(1, 0, 0),))
    T = applyFormatting(T, 'condimentum', dict(font='Arial Italic', fill=(0, 1, 0),))
    while len(T):
        T = textBox(T, (20, 20, width() - 40, height() - 40))

  • admin

    I guess you are making to complex 🙂

    import re
    # a list of words to format differently
    wordsToItalicize = ["italic", "bar"]
    # your text
    txt = '''foo bar italic bar foo italic bar foo'''
    # the default formatting as a reusable dict
    defaultFormatting = dict(
        fill=(0, .2, .1, 1)
    # the italic formatting as a reusable dict
    italicFormatting = dict(
        fill=(1, 0, 0, 1)
    # compile a regex 
    r = re.compile(f"({'|'.join(wordsToItalicize)})")
    # start an empty formatted string
    ftxt = FormattedString()
    # start loop over all the items with the regex
    for item in r.split(txt):
        # choose the correct formatting
        if item in wordsToItalicize:
            settings = italicFormatting
            settings = defaultFormatting
        # append the text in the formatting text
        ftxt.append(item, **settings)
    # draw the text
    textBox(ftxt, (10, 10, 100, 100))

Log in to reply