Best Python code snippet using avocado_python
mixej.py
Source:mixej.py  
1import sys2import platform3import json4import logging5SPLIT_KEY = '/ej/'6ITEM_SEP = '\\hspace{0mm}\\\\'7FILE_VERSION = '0.18'8FILE_DATE = '2022/03/26'9FILE_AUTHOR = 'Haruki Ejiri'10FILE_URL = 'https://github.com/ehki/jIEEEtran/'11logger = logging.getLogger(__name__)12def check_load_file(fn, asjson=False):13    """load file if exist else return -1.14    This code load text and json file if exist.15    If the file not exist, return -116    Parameters17    ----------18    fn : str19        Path to the file to load20    asjson : bool21        whether the fn should be loaded using json or normal text file22    Returns23    -------24    int25        0 if success26    """27    logger.info('-- Checking file %s, ' % fn)28    try:29        with open(fn, 'r', encoding='utf-8') as f:30            logger.info('exist, load.')31            if asjson:32                return json.load(f)33            else:34                return f.read()35    except FileNotFoundError:36        logger.info('not found.')37        return -138def save_pairs(fn, pairs):39    """save pairs to the JSON format file with the extensions of ".ejp".40    This code save the pairs to the file in JSON format.41    Parameters42    ----------43    fn : str44        Path to the file to write pairs45    pairs : list of two strings46        for example: [["en1",  "jp1"], ["en2", "jp2"], ["en3", "jp3"]]47    Returns48    -------49    int50        0 if success51    """52    logger.info('-- Saving found pairs to %s, ' % fn)53    with open(fn, 'w', encoding='utf-8') as f:54        json.dump(pairs, f)55    logger.info('done.')56    return 057def divide_aux(fn, pairs):58    """divide comined citation(s) and bibcite(s) in aux file.59    This code divide the combined key(s) in aux file.60    For example, the following citation(s) and bibcite(s) in aux file61    --62    \\citation{englishTest7/ej/japaneseTest7}63    \\bibcite{englishTest7/ej/japaneseTest7}{16}64    --65    will be converted to the following two divided citations and bibitems.66    --67    \\citation{englishTest7,japaneseTest7}68    \\bibcite{englishTest7,japaneseTest7}{16}69    --70    Parameters71    ----------72    fn : str73        Path to the aux file to proceess74    pairs : list of two strings75        for example: [["en1",  "jp1"], ["en2", "jp2"], ["en3", "jp3"]]76    Returns77    -------78    int79        -1 if the file to process not found, 0 if success80    """81    aux = check_load_file(fn)82    if aux == -1:  # file not found83        return -1  # failed84    for k1, k2 in pairs:85        combi = SPLIT_KEY.join([k1, k2])86        # for example, combi is "engkey/ej/jpkey", wehere SPLIT_KEY is "/ej/"87        logger.info('-- Dividing %s into %s and %s' % (combi, k1, k2))88        aux = aux.replace('%s' % combi,89                          '%s,%s' % (k1, k2))90    with open(fn, 'w', encoding='utf-8') as f:91        f.write(aux)92    return 093def divide_bbl(fn, pairs):94    """divide comined bibitem(s) in bbl file.95    This code divide the combined key(s) in bbl file.96    For example, the following combined bibitem(s) in bbl file97    --98    \\bibitem{englishTest5/ej/japaneseTest5}99    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese100    Transaction, Vol.10, No.5, pp.45--60 (2016-3)\\hspace{0mm}\\\\101    å±±ç°~ä¸éã»ä½è¤~次éã»ç°ä¸~ä¸éã»é´æ¨~åéï¼ãæç®ã¿ã¤ãã«ãï¼102    æ¥æ¬èªå¦ä¼ï¼Vol.10ï¼No.5ï¼pp.45--60ï¼2016-3ï¼103    --104    will be converted to the following two divided bibitems.105    --106    \\bibitem{englishTest5}107    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese108    Transaction, Vol.10, No.5, pp.45--60 (2016-3)109    \\bibitem{japaneseTest5}110    å±±ç°~ä¸éã»ä½è¤~次éã»ç°ä¸~ä¸éã»é´æ¨~åéï¼ãæç®ã¿ã¤ãã«ãï¼111    æ¥æ¬èªå¦ä¼ï¼Vol.10ï¼No.5ï¼pp.45--60ï¼2016-3ï¼112    --113    Parameters114    ----------115    fn : str116        Path to the bbl file to proceess117    pairs : list of two strings118        for example: [["en1",  "jp1"], ["en2", "jp2"], ["en3", "jp3"]]119    Returns120    -------121    int122        -1 if the file to process not found, 0 if success123    """124    bbl = check_load_file(fn)125    if bbl == -1:  # file not found126        return -1  # failed127    for k1, k2 in pairs:128        combi = SPLIT_KEY.join([k1, k2])129        # for example, combi is "engkey/ej/jpkey", wehere SPLIT_KEY is "/ej/"130        logger.info('-- Dividing %s into %s and %s' % (combi, k1, k2))131        bbl = bbl.replace(ITEM_SEP, '\n\n\\bibitem{%s}' % k2)132        bbl = bbl.replace('\\bibitem{%s}' % combi, '\\bibitem{%s}' % k1)133    logger.info('-- Saving divided bbl to %s, ' % fn)134    with open(fn, 'w', encoding='utf-8') as f:135        f.write(bbl)136    logger.info('done.')137    return 0  # successfully finished138def find_pairs(fn, aux):139    """find english/japanese pair from string in aux.140    This code find and store english/japanese pair.141    Reading each line in aux strings, the engligh and japanese keys142    are extracted if SPLIT_KEY is in the line.143    If the combined english/japanese keys in the aux file,144    the pairs are stored to the external JSON file145    Parameters146    ----------147    fn : str148        Path to the aux file to proceess149    aux : strings in aux file150        loaded string151    Returns152    -------153    int154        0 if no combined keys found155        num-of-pairs if successfully processed156    """157    pairs = []158    logger.info('-- ')159    for line in aux.split('\n'):160        if SPLIT_KEY not in line or '\\citation' not in line:161            continue162        # the line contains \citation and /ej/163        for ln in line.replace('\\citation{', '').replace('}', '').split(','):164            # convert '\citation{hoge1/ej/hoge2}' to 'hoge1/ej/hoge2'165            if len(ln.split(SPLIT_KEY)) == 2:166                pairs.append(ln.split(SPLIT_KEY))167                # store as ['hoge1', 'hoge2'] pairs168                logger.info('%s' % str(ln.split(SPLIT_KEY)))169    if len(pairs) == 0:170        logger.info('No combined keys found.')171        ret = 0172    if len(pairs) > 0:173        logger.info(' %d combined keys found.' % len(pairs))174        ret = pairs175        save_pairs(fn, pairs)176    return ret177def combine_aux(fn, pairs):178    """combine divided citation(s) and bibcite(s) in aux file.179    This code combine the divided key(s) in aux file.180    For example, the following two divided citation(s) and bibcite(s)181    in aux file182    --183    \\citation{englishTest7,japaneseTest7}184    \\bibcite{englishTest7,japaneseTest7}{16}185    --186    will be converted to the following combined citations and bibitems.187    --188    \\citation{englishTest7/ej/japaneseTest7}189    \\bibcite{englishTest7/ej/japaneseTest7}{16}190    --191    Parameters192    ----------193    fn : str194        Path to the aux file to proceess195    pairs : list of two strings196        for example: [["en1",  "jp1"], ["en2", "jp2"], ["en3", "jp3"]]197    Returns198    -------199    int200        -1 if the file to process not found, 0 if success201    """202    aux = check_load_file(fn)203    if aux == -1:  # file not found204        return -1  # failed205    for k1, k2 in pairs:206        combi = SPLIT_KEY.join([k1, k2])207        # for example, combi is "engkey/ej/jpkey", wehere SPLIT_KEY is "/ej/"208        logger.info('-- Combining %s and %s to %s' % (k1, k2, combi))209        aux = aux.replace('%s,%s' % (k1, k2), '%s' % combi)210    logger.info('-- Saving combined aux to %s, ' % fn)211    with open(fn, 'w', encoding='utf-8') as f:212        f.write(aux)213    logger.info('done.')214def combine_bbl(fn, pairs):215    """combine divided bibitem(s) in bbl file.216    This code divide the combined key(s) in bbl file.217    For example, the following two divided bibitem(s) in bbl file218    --219    \\bibitem{englishTest5}220    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese221    Transaction, Vol.10, No.5, pp.45--60 (2016-3)222    \\bibitem{japaneseTest5}223    å±±ç°~ä¸éã»ä½è¤~次éã»ç°ä¸~ä¸éã»é´æ¨~åéï¼ãæç®ã¿ã¤ãã«ãï¼224    æ¥æ¬èªå¦ä¼ï¼Vol.10ï¼No.5ï¼pp.45--60ï¼2016-3ï¼225    --226    will be converted to the following combined citations and bibitems.227    --228    \\bibitem{englishTest5/ej/japaneseTest5}229    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese230    Transaction, Vol.10, No.5, pp.45--60 (2016-3)\\hspace{0mm}\\\\231    å±±ç°~ä¸éã»ä½è¤~次éã»ç°ä¸~ä¸éã»é´æ¨~åéï¼ãæç®ã¿ã¤ãã«ãï¼232    æ¥æ¬èªå¦ä¼ï¼Vol.10ï¼No.5ï¼pp.45--60ï¼2016-3ï¼233    --234    Parameters235    ----------236    fn : str237        Path to the aux file to proceess238    pairs : list of two strings239        for example: [["en1",  "jp1"], ["en2", "jp2"], ["en3", "jp3"]]240    Returns241    -------242    int243        -1 if the file to process not found, 0 if success244    """245    bbl = check_load_file(fn)246    if bbl == -1:  # file not found247        return -1  # failed248    for k1, k2 in pairs:249        combi = SPLIT_KEY.join([k1, k2])250        # for example, combi is "engkey/ej/jpkey", wehere SPLIT_KEY is "/ej/"251        logger.info('-- Combining %s and %s to %s' % (k1, k2, combi))252        bbl = bbl.replace('\n\n\\bibitem{%s}' % k2, ITEM_SEP)253        bbl = bbl.replace('\\bibitem{%s}' % k1,254                          '\\bibitem{%s}' % combi)255    logger.info('-- Saving combined bbl to %s, ' % fn)256    with open(fn, 'w', encoding='utf-8') as f:257        f.write(bbl)258    logger.info('done.')259def divide_ej_key(bn):260    """divide combined english and japanese bibiteems in bbl and aux file.261    This code divide the combined key(s) in aux and bbl file.262    For example, the following combined bibitem(s) in bbl file263    --264    \\bibitem{englishTest5/ej/japaneseTest5}265    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese266    Transaction, Vol.10, No.5, pp.45--60 (2016-3)\\hspace{0mm}\\\\267    å±±ç°~ä¸éã»ä½è¤~次éã»ç°ä¸~ä¸éã»é´æ¨~åéï¼ãæç®ã¿ã¤ãã«ãï¼268    æ¥æ¬èªå¦ä¼ï¼Vol.10ï¼No.5ï¼pp.45--60ï¼2016-3ï¼269    --270    will be converted to the following two divided bibitems.271    --272    \\bibitem{englishTest5}273    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese274    Transaction, Vol.10, No.5, pp.45--60 (2016-3)275    \\bibitem{japaneseTest5}276    å±±ç°~ä¸éã»ä½è¤~次éã»ç°ä¸~ä¸éã»é´æ¨~åéï¼ãæç®ã¿ã¤ãã«ãï¼277    æ¥æ¬èªå¦ä¼ï¼Vol.10ï¼No.5ï¼pp.45--60ï¼2016-3ï¼278    --279    The following two combined citation(s) and bibcite(s) in aux file280    --281    \\citation{englishTest7/ej/japaneseTest7}282    \\bibcite{englishTest7/ej/japaneseTest7}{16}283    --284    will also be converted to the following combined citations and bibitems.285    --286    \\citation{englishTest7}287    \\citation{japaneseTest7}288    \\bibcite{englishTest7}{1}289    \\bibcite{japaneseTest7}{16}290    --291    The first process during LaTeX compile, there would no bbl file.292    If the bbl file not exist, the dividing process would be skipped.293    A list of english/japanese pairs will be extracted from aux file,294    and if will be saved in the JSON file with295    ".ejp" (english-japanese-pair) extension296    Parameters297    ----------298    bn : str299        Target file to process without extension.300        if your target tex file is '/DIRNAME/main.tex'301        the bn would be '/DIRNAME/main'302    Returns303    -------304    int305        -1 if the file to process not found306        0 if no combined keys found307        num-of-pairs if successfully processed308    """309    logger.info('--')310    logger.info('-- Dividing combinecd keys.')311    aux = check_load_file(bn + '.aux')312    if aux == -1:  # aux file not found313        return -1  # abort314    logger.info('-- Search combined keys from %s.aux.' % bn)315    pairs = find_pairs(bn + '.ejp', aux)316    if pairs == 0:  # no combined keys317        return 0  # probably already divided318    divide_aux(bn + '.aux', pairs)319    divide_bbl(bn + '.bbl', pairs)320    return len(pairs)321def combine_ej_key(bn):322    """combine english and japanese bibiteems in bbl and aux file.323    This code combine the divided key(s) in aux and bbl file.324    For example, the following divided bibitem(s) in bbl file325    --326    \\bibitem{englishTest5}327    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese328    Transaction, Vol.10, No.5, pp.45--60 (2016-3)329    \\bibitem{japaneseTest5}330    å±±ç°~ä¸éã»ä½è¤~次éã»ç°ä¸~ä¸éã»é´æ¨~åéï¼ãæç®ã¿ã¤ãã«ãï¼331    æ¥æ¬èªå¦ä¼ï¼Vol.10ï¼No.5ï¼pp.45--60ï¼2016-3ï¼332    --333    will be converted to the following two divided bibitems.334    --335    \\bibitem{englishTest5/ej/japaneseTest5}336    I.~Yamada, J.~Sato, S.~Tanaka, S.~Suzuki: ``Article title'', Japanese337    Transaction, Vol.10, No.5, pp.45--60 (2016-3)\\hspace{0mm}\\\\338    å±±ç°~ä¸éã»ä½è¤~次éã»ç°ä¸~ä¸éã»é´æ¨~åéï¼ãæç®ã¿ã¤ãã«ãï¼339    æ¥æ¬èªå¦ä¼ï¼Vol.10ï¼No.5ï¼pp.45--60ï¼2016-3ï¼340    --341    The following two divided citation(s) and bibcite(s) in aux file342    --343    \\citation{englishTest7}344    \\citation{japaneseTest7}345    \\bibcite{englishTest7}{1}346    \\bibcite{japaneseTest7}{16}347    --348    will also be converted to the following combined citations and bibitems.349    --350    \\citation{englishTest7/ej/japaneseTest7}351    \\bibcite{englishTest7/ej/japaneseTest7}{16}352    --353    Parameters354    ----------355    bn : str356        Target file to process without extension.357        if your target tex file is '/DIRNAME/main.tex'358        the bn would be '/DIRNAME/main'359    Returns360    -------361    int362        -1 if the file to process not found363        0 if no combined keys found364        num-of-pairs if successfully processed365    """366    logger.info('--')367    logger.info('-- Combining divided keys.')368    pairs = check_load_file(bn + '.ejp', asjson=True)369    if pairs == -1:  # file not found370        return -1371    if len(pairs) == 0:  # no combined keys372        return 0373    combine_aux(bn + '.aux', pairs)374    combine_bbl(bn + '.bbl', pairs)375    return len(pairs)376if __name__ == '__main__':377    logger = logging.getLogger()378    logger.setLevel(logging.INFO)379    sh = logging.StreamHandler()380    logger.addHandler(sh)381    logger.info(382        'This is python version %s ' % platform.python_version())383    logger.info(384        'mixje.py version %s (%s) by %s.' %385        (FILE_VERSION, FILE_DATE, FILE_AUTHOR)386    )387    logger.info('See web site: %s' % FILE_URL)388    try:389        fname = sys.argv[1]390        logger.info('Target: %s' % fname)391    except IndexError:392        logger.info('Fatal error: You must assign target.')393        sys.exit(0)394    sk = divide_ej_key(fname)395    if sk > 0:  # combined keys existed396        logger.info('-- Fin, %d keys were divided.' % sk)397        sys.exit(0)398    elif sk < 0:  # Abort399        sys.exit(0)400    ck = combine_ej_key(fname)401    if ck != 0:402        # print('-- %d divided citation keys were successfully combined' % ck)403        logger.info('-- Fin, %d keys were combined.' % ck)404        sys.exit(0)405    with open(sys.argv[1] + '.ejp', 'w', encoding='utf-8') as f:406        json.dump([], f)407    logger.info(408        '-- No cmobined nor divided citation key in the aux file')...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
