简体   繁体   English

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

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

I want to read a dictionary from a text file.我想从文本文件中读取字典。 This dictionary seems like {'key': [1, ord('@')]} .这本字典看起来像{'key': [1, ord('@')]} I read about eval() and literal_eval() , but none of those two will work due to ord() .我读到了eval()literal_eval() ,但是由于ord() ,这两个都不起作用。

I also tried json.loads and json.dumps , but no positive results.我也试过json.loadsjson.dumps ,但没有积极的结果。

Which other way could I use to do it?我可以使用其他哪种方式来做到这一点?

So Assuming you read the text file in with open as a string and not with json.loads you could do some simple regex searching for what is between the parenthesis of ord eg ord('@') -> @因此,假设您使用open作为字符串而不是使用json.loads读取文本文件,您可以执行一些简单的正则表达式来搜索 ord 括号之间的内容,例如ord('@') -> @

This is a minimal solution that reads everything from the file as a single string then finds all instances of ord and places the integer representation in an output list called ord_ .这是一个最小的解决方案,它将文件中的所有内容作为单个字符串读取,然后查找 ord 的所有实例并将 integer 表示形式放在名为ord_的 output 列表中。 For testing this example myfile.txt was a text file with the following in it为了测试这个例子myfile.txt是一个文本文件,其中包含以下内容

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

"key2": [1, "ord('K')"]} "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. json.dump() and json.load() will not work because ord() is not JSON Serializable (meaning that the function cannot be a JSON object.
  • Yes, eval is really bad practice, I would never recommend it to anyone for any use.是的, eval真的是不好的做法,我永远不会将它推荐给任何人用于任何用途。

The best way I can think of to solve this is to use conditions and an extra list.我能想到的解决这个问题的最好方法是使用条件和额外的列表。

# 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