1

I have some text, with specific words highlighted,

from termcolor import colored
text='left foot right foot left foot right. Feet in the day, feet at night.'
l1=['foot','feet']
result = " ".join(colored(t,'white','on_red') if t in l1 else t for t in text.lower().split())
print(result)

I am relatively new to pyhthon, and wonder if there is a way to create a visual/plot to show the sentences and print it to screen. I only want to print a few sentences. Would be great if I could print entire story (100k words) to a doc file.

I thought of plotting the highlighted sentence, and thought of matplotlib, Partial coloring of text in matplotlib, but do not think this would work. Is there another visual I can use?

I would like to plot and save a png, etc if possible: enter image description here

frank
  • 3,036
  • 7
  • 33
  • 65

1 Answers1

0

Very interesting question. I made you a solution for a few sentences case, but if you want to create this for the whole document I would recommend to use any PDF writer.

import matplotlib.pyplot as plt

def color_code():
    text='left foot right foot left foot right. Feet in the day, feet at night.'
    text_split = text.split(" ")
    l1=['foot','feet']

    # Pixels where you want to start first word
    start_x = 20
    start_y = 450

    # Decide what is the last pixel for writing words in one line
    end = 600

    # Whitespace in pixels
    whitespace = 8

    # Create figure
    figure = plt.figure()

    # From renderer we can get textbox width in pixels
    rend = figure.canvas.get_renderer()
    for word in (text_split):
        # Text box parameters and colors
        bbox = dict(boxstyle="round,pad=0.3", fc="red", ec="b", lw=2)

        # Check if word contains "foot", "feet", "foot." or "feet." or caps locked.
        # Depending what you are trying to achieve.
        if (word in l1 or word.replace('.','') in l1 or word.lower() in l1):
            txt = plt.text(start_x, start_y, word, color="black", bbox=bbox,transform=None)
        else:
            txt = plt.text(start_x, start_y, word, transform=None)
        # Textbox width
        bb = txt.get_window_extent(renderer=rend)

        # Calculate where next word should be written
        start_x = bb.width + start_x + whitespace

        # Next line if end parameter in pixels have been crossed
        if start_x >= end:
            start_x = 20
            start_y -= 40

    # Skip plotting axis
    plt.axis("off")
    # Save and plot figure
    plt.savefig("plot.png")
    plt.show()


color_code()

Result with longer string should look like this: Plot

Heikura
  • 1,009
  • 3
  • 13
  • 27