[英]Plot coloured text in python
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.我对 pyhthon 比较陌生,想知道是否有办法创建视觉/绘图来显示句子并将其打印到屏幕上。 I only want to print a few sentences.
我只想打印几句话。 Would be great if I could print entire story (100k words) to a doc file.
如果我可以将整个故事(10 万字)打印到 doc 文件中,那就太好了。
I thought of plotting the highlighted sentence, and thought of matplotlib, Partial coloring of text in matplotlib , but do not think this would work.我想到了绘制突出显示的句子,并想到了 matplotlib, matplotlib 中文本的部分着色,但认为这行不通。 Is there another visual I can use?
我可以使用其他视觉效果吗?
I would like to plot and save a png, etc if possible:如果可能,我想绘制并保存 png 等:
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.
我为您提供了几个句子案例的解决方案,但是如果您想为整个文档创建此解决方案,我建议您使用任何 PDF 编写器。
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:较长字符串的结果应如下所示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.