Advertisement
Mark2020H

Class file that provides a choice in colors printing chars to terminal

May 7th, 2023 (edited)
988
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.17 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. # python class file that allows  to read in a file split paragraphs then  print each line of
  4. # paragraph and its characters  within that line  in chosen colour  to a terminal
  5. # after each paragraph you  are then prompted  for input donated by $:  following which the next
  6. # paragraph will be printed  as per above sequence
  7. # Good practice for presentations  to explain points  whilst presenting media of some type  using a terminal
  8. # This also aids as a prompt for to remind yourself of key issue  you need to discuss
  9.  
  10. # MD Harrington 08/05/2023  facebook link  https://www.facebook.com/mark.harrington.14289/
  11. # Instagram Link https://www.instagram.com/markukh2021/
  12.  
  13. import time
  14.  
  15.  
  16. class TextReader:
  17.     def __init__(self, filename):
  18.         self.filename = filename
  19.  
  20.     def read_file(self):
  21.         color_code = self.get_color_code()
  22.         with open(self.filename, 'r') as f:
  23.             text = f.read()
  24.         return text, color_code
  25.  
  26.     def get_color_code(self):
  27.         color = input("Select a color for the text (red/green/blue/purple/white/yellow/cyan): ")
  28.         color_codes = {'black': '\033[30m', 'red': '\033[31m', 'green': '\033[32m',
  29.                        'yellow': '\033[33m', 'blue': '\033[34m', 'purple': '\033[35m',
  30.                        'cyan': '\033[36m', 'white': '\033[37m'}
  31.         if color in color_codes:
  32.             return color_codes[color]
  33.         else:
  34.             print("Invalid color selected, defaulting to black.")
  35.             return color_codes["white"]
  36.  
  37.     def print_text(self, text, color_code):
  38.         paragraphs = text.split('\n\n')
  39.         for paragraph in paragraphs:
  40.             print(color_code, end="")
  41.             lines = paragraph.split('\n')
  42.             for line in lines:
  43.                 for char in line:
  44.                     print(char, end='', flush=True)
  45.                     time.sleep(0.03)
  46.                 print()
  47.             print("\033[0m")   # reset color code
  48.             input("$:")
  49.  
  50.  
  51. def main():
  52.     filename = "instructions"
  53.     tr = TextReader(filename)
  54.     text, color_code = tr.read_file()
  55.     tr.print_text(text, color_code)
  56.  
  57.  
  58. if __name__ == '__main__':
  59.     main()
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement