Advertisement
gregwa

FCM #152 - rgb2pickle.py

Dec 6th, 2019
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.08 KB | None | 0 0
  1. #! /usr/bin/env python
  2. #  -*- coding: utf-8 -*-
  3.  
  4. # rgb2pickle.py
  5.  
  6.  
  7. import pickle
  8.  
  9. myList = []
  10. myDict = {}
  11.  
  12.  
  13. def read_file_textlines(filname):
  14.     """read text from file and return the file content in a list of lines"""
  15.     import io
  16.     signal = None
  17.     try:
  18.         with open(filname, "r") as f:
  19.             text_lines = f.read().splitlines()
  20.             signal = True   # Done.
  21.             return signal, text_lines
  22.     except IOError:
  23.         signal = False   # Something went wrong !!
  24.         return signal, ''
  25.  
  26.  
  27. # ---txt tool section------------------------------------------------------ #
  28. def emptystring(txt):
  29.     if txt == '':   # txt == '0'
  30.         txt = '00'
  31.     return txt
  32.  
  33.  
  34. def onelychrs(txt):
  35.     if len(txt) < 2:
  36.         txt = f"0{txt}"
  37.     return txt
  38.  
  39.  
  40. def chkzero(txt):
  41.     if txt == '0':
  42.         txt = '00'
  43.     return txt
  44.  
  45.  
  46. def dec2hex(txt):
  47.     txt = hex(int(txt)).lstrip("0x")
  48.     txt = txt.upper()
  49.     txt = onelychrs(txt)
  50.     txt = chkzero(txt)
  51.     return txt
  52.  
  53.  
  54. def txt2dict(myList):
  55.     i = 0
  56.     aDict = {}
  57.     for item in myList:
  58.         newList = []
  59.         # pick name and clean it for tab
  60.         name = item[13:].lstrip("\t")
  61.         name = name.rstrip()
  62.         # pick RGB values (dec)
  63.         R = item[0:3].lstrip()
  64.         R = emptystring(R)
  65.         G = item[4:7].lstrip()
  66.         G = emptystring(G)
  67.         B = item[8:11].lstrip()
  68.         B = emptystring(B)
  69.         # convert dec2hex value
  70.         H1 = dec2hex(R)
  71.         H2 = dec2hex(G)
  72.         H3 = dec2hex(B)
  73.         # build a hash value
  74.         H = f"#{H1}{H2}{H3}"
  75.         # make a list with a new column structure
  76.         newList.append(name)
  77.         newList.append(R)
  78.         newList.append(G)
  79.         newList.append(B)
  80.         newList.append(H)
  81.         aDict[i] = newList
  82.         i += 1
  83.     return aDict
  84.  
  85.  
  86. # Main code starts here...
  87. signal, myList = read_file_textlines('rgb.txt')
  88. print(f'Signal is: {signal}')
  89.  
  90. myDict = txt2dict(myList)
  91. fn = 'list.pkl'
  92. outfile = open(fn, 'wb')
  93. pickle.dump(myDict, outfile)
  94. outfile.close()
  95.  
  96. print('Finished!')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement