Python Forum

Full Version: Saving python cmd output into a text file with colours
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
from colorama import Fore, Back, Style, init
import fpdf
from fpdf import FPDF


init()





paragraph = 'Whatever blame emerges! Its gasoline avoids the prison. The unlimited mania varies an exotic garage. A curtain farms? The sunrise fells an assorted companion around the jet.'


key_words = ['blame', 'avoids', 'unlimited', 'exotic']



def highlight(word):
    if word in key_words:
        return Fore.RED + str(word) + Fore.RESET
    
    else:
        return str(word)


textpara = paragraph.strip().split(' ')
colored_words = list(map(highlight, textpara))
final = " ".join(colored_words)
print (final)
I have created a code which highlight the keywords in a paragraph. I ran it in the cmd and it works fine (output is in the attachment). How do I save this output into file or PDF with colours highlighted so I don't have to re run the code again?

I tried to copy and paste the output into a text file but the colours did not show up

Thanks for the help
I'm not sure that's possible. I think if you want to save colored text you may need to do it in another format, such as HTML with tags to color the text.
i think the easiest way would be to save it as an html file. Change the paragraph section to encompass the keywords with bold since you dont have more than one color <b>keyword</b>. And if you needed more colors wrap in font tags like: <font color="red">This is some text!</font>

Then just open the file in a browser to view it.