Search code examples
pythonblender

Declare everything after a character


I'm trying to write a Python script for Blender that will delete all shape keys that have KK at the start of them.

I have many shapekeys which start with KK but have different stuff after KK, for example KK_Eyebrows or KK_Nose

I managed to use this:

import bpy

def deleteShapekeyByName(oObject, sShapekeyName):
    
    # setting the active shapekey
    iIndex = oObject.data.shape_keys.key_blocks.keys().index(sShapekeyName)
    oObject.active_shape_key_index = iIndex
    
    # delete it
    bpy.ops.object.shape_key_remove()

oActiveObject = bpy.context.active_object
deleteShapekeyByName(oActiveObject, "KK_Shapekey")

But I have to manually put in every shapekey name I want to remove, instead of removing everything that has KK in it.

Thanks in advance


Solution

  • If you can get a list of the shapekey names you can do something like this.

    import bpy
    
    def deleteShapekeyByName(oObject, sShapekeyName):
        
        # setting the active shapekey
        iIndex = oObject.data.shape_keys.key_blocks.keys().index(sShapekeyName)
        oObject.active_shape_key_index = iIndex
        
        # delete it
        bpy.ops.object.shape_key_remove()
        
    # Not sure if this returns the right keys for you. you may have to change .object to .active_object
    s_key_names = list(bpy.context.object.data.shape_keys.key_blocks.keys())
    oActiveObject = bpy.context.active_object
    
    for s_k_n in s_key_names:
    
        if s_k_n.startswith('KK'):
    
            deleteShapekeyByName(oActiveObject, s_k_n)