[英]Escape LaTeX Characters in Python3 Dictionary
I have a dictionary that needs to have values properly escaped for LaTeX consumption. 我有一本字典,需要适当地转义以消耗LaTeX的值。
Steps: 脚步:
Get some JSON from a text file into a python dictionary. 从文本文件中获取一些JSON到python字典中。
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: 从
d1
和tex
d2
,注意只有叶节点被转义:
>>>> 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
. 如您所见,我被困在重新创建
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. 最初,我只是想进行一次dict理解,即使用
tex
替换字符串中的每个值,但是我没有意识到您有嵌套的列表,dict。 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. 看起来有点疯狂,但是它的工作是遍历
d1
每个值作为key,value
元组,评估它的类型,然后根据需要更改每个值。 is it the simplest solution? 这是最简单的解决方案吗? probably not.
可能不是。 But it works and is pythonic in the sense that it doesnt import any external modules
但是它可以工作并且在不导入任何外部模块的意义上是pythonic
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.