Python Forum
Saving python cmd output into a text file with colours - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Saving python cmd output into a text file with colours (/thread-15637.html)



Saving python cmd output into a text file with colours - kapilan15 - Jan-25-2019

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


RE: Saving python cmd output into a text file with colours - ichabod801 - Jan-25-2019

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.


RE: Saving python cmd output into a text file with colours - metulburr - Jan-25-2019

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.