[英]How could I read a dictionary that contains a function from a text file?
我想從文本文件中讀取字典。 這本字典看起來像{'key': [1, ord('@')]}
。 我讀到了eval()
和literal_eval()
,但是由於ord()
,這兩個都不起作用。
我也試過json.loads
和json.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.