辞書のキーのシノニム変換(同義語を翻訳)

  • パラメータ名等、複数パラメータ名がでてきて、コード上で同義語として扱いたい場合に、辞書を変換する.

  • 主に、プロットのルーチン中で、default.confの設定名を変更したいとき.

    • (ただし、旧コードもエラーなしに走るようにしたい.)

  • 辞書のキー名を変換して、旧キー名を新キー名に変換し、どちらのキーワードでも通るようにしたい.


コード

import os, sys, re, json5

# ========================================================= #
# ===  synonymize__keywords.py                          === #
# ========================================================= #

def synonymize__keywords( dictionary=None, synonym=None ):

    # ------------------------------------------------- #
    # --- [1] load dictionary & synonym             --- #
    # ------------------------------------------------- #
    if ( dictionary is None ):
        print( "[synonymize__keywords.py] dictionary == ??? " )
    else:
        if ( type( dictionary ) is str ):
            if ( os.path.exists( dictionary ) ):
                with open( dictionary, "r" ) as f:
                    dictionary = json5.load( f )
            else:
                print( "[synonymize__keywords.py] cannnot find {} ".format( dictionary ) )
                sys.exit()
    
    if ( synonym is None ):
        print( "[synonymize__keywords.py] synonym == ??? " )
    else:
        if ( type( synonym ) is str ):
            if ( os.path.exists( synonym ) ):
                with open( synonym, "r" ) as f:
                    synonym = json5.load( f )
            else:
                print( "[synonymize__keywords.py] cannnot find {} ".format( synonym ) )
                sys.exit()
                
    # ------------------------------------------------- #
    # --- [2] replace synonym                       --- #
    # ------------------------------------------------- #
    ret = { **dictionary }
    for key in dictionary.keys():
        if ( key in synonym ):
            ret[ synonym[key] ] = ret.pop( key )
        else:
            ret[ key ]            = ret.pop( key )
    return( ret )


# ========================================================= #
# ===   Execution of Pragram                            === #
# ========================================================= #

if ( __name__=="__main__" ):

    dictionary = "test/synonymize__keywords.json"
    synonym    = "test/synonym.json"
    ret        = synonymize__keywords( dictionary=dictionary, synonym=synonym )
    print( ret )

パラメータ ( parameters.json )

{

    "aaa" : "a3",
    "bbbb": "b4",
    "cc"  : "c2",
    
}

同義語リスト ( thesaurus.json )

{
    
    "aaa"  : "AAA",
    "bbbb" : "BBBB", 

}

出力結果

$ kent@maxwell ~/.../python/synonymize__keywords $ python pyt/synonymize__keywords.py
{'AAA': 'a3', 'BBBB': 'b4', 'cc': 'c2'}