繁体   English   中英

如何从文本文件中读取包含 function 的字典?

[英]How could I read a dictionary that contains a function from a text file?

我想从文本文件中读取字典。 这本字典看起来像{'key': [1, ord('@')]} 我读到了eval()literal_eval() ,但是由于ord() ,这两个都不起作用。

我也试过json.loadsjson.dumps ,但没有积极的结果。

我可以使用其他哪种方式来做到这一点?

因此,假设您使用open作为字符串而不是使用json.loads读取文本文件,您可以执行一些简单的正则表达式来搜索 ord 括号之间的内容,例如ord('@') -> @

这是一个最小的解决方案,它将文件中的所有内容作为单个字符串读取,然后查找 ord 的所有实例并将 integer 表示形式放在名为ord_的 output 列表中。 为了测试这个例子myfile.txt是一个文本文件,其中包含以下内容

{"key": [1, "ord('@')"],

"key2": [1, "ord('K')"]}

import json
import re
with open(r"myfile.txt") as f:
    json_ = "".join([line.rstrip("\n") for line in f])

rgx = re.compile(r"ord\(([^\)]+)\)")
rgd = rgx.findall(json_)
ord_ = [ord(str_.replace(r"'", "")) for str_ in rgd]
  • json.dump() and json.load() will not work because ord() is not JSON Serializable (meaning that the function cannot be a JSON object.
  • 是的, eval真的是不好的做法,我永远不会将它推荐给任何人用于任何用途。

我能想到的解决这个问题的最好方法是使用条件和额外的列表。

# data.json = {'key': [1, ['ord', '@']]}    # first one is function name, second is arg
with open("data.json") as f:
    data = json.load(f)
# data['key'][1][0] is "ord"
if data['key'][1][0] == "ord":
    res = ord(data['key'][1][1])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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