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:
