سؤال

Good evening, I have python object of this type. Is here any way to convert it to String, edit, and convert back?

 <class 'matplotlib.transforms.CompositeGenericTransform'>

When I print it by print(variable) it looks like this:

CompositeGenericTransform(CompositeGenericTransform(CompositeGenericTransform(CompositeGenericTransform(CompositeGenericTransform(TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())), CompositeGenericTransform(BboxTransformFrom(TransformedBbox(Bbox('array([[ -19.5      ,  -10.7983871],\n       [ 221.5      ,  140.7983871]])'), TransformWrapper(BlendedAffine2D(IdentityTransform(),IdentityTransform())))), BboxTransformTo(TransformedBbox(Bbox('array([[ 0.125,  0.25 ],\n       [ 0.9  ,  0.9  ]])'), BboxTransformTo(TransformedBbox(Bbox('array([[ 0.,  0.],\n       [ 8.,  6.]])'), Affine2D(array([[ 80.,   0.,   0.],
       [  0.,  80.,   0.],
       [  0.,   0.,   1.]])))))))), Affine2D(array([[ 0.99968918, -0.02493069,  6.98903935],
       [ 0.02493069,  0.99968918, -8.59039721],
       [ 0.        ,  0.        ,  1.        ]]))), Affine2D(array([[ 0.99968918, -0.02493069,  6.93499095],
       [ 0.02493069,  0.99968918, -7.14592338],
       [ 0.        ,  0.        ,  1.        ]]))), Affine2D(array([[ 0.99968918, -0.02493069,  6.88226449],
       [ 0.02493069,  0.99968918, -6.30113809],
       [ 0.        ,  0.        ,  1.        ]]))), Affine2D(array([[ 0.99968918, -0.02493069,  6.96735103],
       [ 0.02493069,  0.99968918, -7.27368166],
       [ 0.        ,  0.        ,  1.        ]])))
هل كانت مفيدة؟

المحلول

You can do that with Pickle, it is an object serialization library for Python.

نصائح أخرى

You can use pickle with dumps and loads, but it may be fragile. Not advised.

import pickle

x  = {'a':1,'b':2}
out = pickle.dumps(x)
out = out.replace("I1","I66")
x2 = pickle.loads(out)
print x2 # {'a': 66, 'b': 2} 

In general, this is not doable. Most objects cannot be constructed from their str representation.* (Some objects can be constructed from their repr, but you shouldn't rely on that.)

In specific cases, you can of course write a specific parser for whatever the type's str is.

But this is almost always a bad idea. Instead, choose an interchange format, then write code to convert your object to that interchange format and back. Many objects (especially in the NumPy family) already know how to render themselves as/construct themselves from various textual formats, like CSV or JSON, so it's just as matter of calling astext and fromtext or tojson and fromjson or whatever.


* Even strings can't be constructed from their str representation; it's really only numbers and the basic collections that can.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top