I was using pickle to load and unload data from a file. Before putting it in the file I wanted to kinda jumble up the words. I succeeded in Encoding and Decoding a dict but it then came out as a string. So I broke the dictionary into chunks of strings. Now the problem is fixing it. I can successfully fix a dictionary like this -
, but not one like this -
I appreciate any help on how I could fix it for this to happen. Sorry if my code is a bit messy but here it is -
The save and load file can help tell you how it works
1 |
{ 'Hello' : 'Bye' } |
1 |
{ 'Opposite' : { 'Hello' : 'Goodbye' }} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
class FileWorker(): def __init__( self ): self .offsets = [] def Save( self , obj): with open ( 'DATA.txt' , 'wb' ) as file : pickle.dump( self .ENCODE( self .BREAK(obj)), file ) def Load( self , index = 0 ): with open ( 'DATA.txt' , 'rb' ) as file : return self .FIX( self .DECODE(pickle.load( file ), index)) def BREAK( self , obj): output = '' print (obj) for item in obj: if type (item) = = type ([]) or type (item) = = type ({}) or type (item) = = type (( 0 ,)): print ( f 'Extra for {item}' ) output + = self .BREAK(item) elif type (obj[item]) = = type ([]) or type (obj[item]) = = type ({}) or type (obj[item]) = = type (( 0 ,)): obj[item] = self .BREAK(obj[item]) output + = str (item) + ' ' if type (obj) = = dict : output + = ', ' + str (obj[item]) return output def FIX( self , obj): if ',' not in obj: return obj.split() else : DataArray = obj.split( ' ' ) output = {} count = 0 for data in DataArray: count + = 1 if ',' in data: print (DataArray) try : try : DataArray[count] = int (DataArray[count]) except : pass DataArray[count - 2 ] = int (DataArray[count - 2 ]) except : pass print (DataArray) output.update({DataArray[count - 2 ] : DataArray[count]}) return output def ENCODE( self , obj): self .offsets.append([]) output = '' count = 0 countTo = len (obj) while True : if count = = countTo: break while True : offset = random.randint( 0 , len (obj) - 1 ) if offset not in self .offsets[ len ( self .offsets) - 1 ]: break self .offsets[ len ( self .offsets) - 1 ].append(offset) output + = obj[offset] count + = 1 return output def DECODE( self , obj, index = 0 ): output = '' count = 0 for number in self .offsets[index]: charIndex = self .offsets[index].index(count) output + = obj[charIndex] count + = 1 return output |
The save and load file can help tell you how it works