简体   繁体   中英

Escape LaTeX Characters in Python3 Dictionary

I have a dictionary that needs to have values properly escaped for LaTeX consumption.

Steps:

Get some JSON from a text file into a python dictionary.

d1 = {'a': 'art', 'b': 'a_$b', 'c': ['_#', 'h'], 'd': {'e': 4, 'f#_a': {'g': '^_$#&'}}}

Make a dictionary of all items to convert:

tex = {
    '&':  '\&',
    '%':  '\%', 
    '$':  '\$', 
    '#':  '\#', 
    '_':  '\_', 
    '^':  '\^', 
}

Make d2 from d1 and tex , noting that only leaf nodes are escaped:

>>>> d2 = unknown code here
>>>> d2
{'a': 'art', 'b': 'a\_\$b', 'c': ['\_\#', 'h'], 'd': {'e': 4, 'f#_a': {'g': '\^\_\$\#\&'}}}

Here is a messy rough draft of my attempt so far. As you can see, I am stuck on recreating d2 .

def texEscape(originalKey, d):                                                                                                              
    if isinstance(d, dict):
        for k, v in d.items():
            if isinstance(v, str):
                print(k)
                print(v)
                print()
            else:
                texEscape(originalKey, v)
    elif isinstance(d, list):
        for i in d:
            texEscape(originalKey, i)
    else:
        print(originalKey)
        print(d)
        print()

originally i was just going to do a dict comprehension where every value as a string was being replaced using tex but I didn't realize you had nested lists,dicts. This works.

>>> tex = {
            '&':  '\&',
            '%':  '\%',
            '$':  '\$',
            '#':  '\#',
            '_':  '\_',
            '^':  '\^',
        }
>>> def change(x):
    key,value = x
    if isinstance(value, dict):
        return key,dict(map(change,value.items()))
    elif isinstance(value, list):
        return key,[''.join(tex[c] if c in tex else c for c in str(x)) for x in value]
    else:
        return key,''.join(tex[c] if c in tex else c for c in str(value))
>>> d1 = {'a': 'art', 'b': 'a_$b', 'c': ['_#', 'h'], 'd': {'e': 4, 'f#_a': {'g': '^_$#&'}}}
>>> d2 = dict(map(change,d1.items()))
>>> d2
{'b': 'a\\_\\$b', 'd': {'e': '4', 'f#_a': {'g': '\\^\\_\\$\\#\\&'}}, 'c': ['\\_\\#', 'h'], 'a': 'art'}

it seems kinda crazy but what it does is iterate through each value of d1 as a key,value tuple, assess what type it is, then change each value as necessary. is it the simplest solution? probably not. But it works and is pythonic in the sense that it doesnt import any external modules

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM