【问题标题】:How to call functions and variables from a dictionary or a json file如何从字典或 json 文件中调用函数和变量
【发布时间】:2020-04-19 06:59:15
【问题描述】:

我正在尝试打印一个字符串,在一行中调用函数和变量。 如【你好! %(job), %(name)s, (function_name)]->[Hello! student, John, This is the function.]

json01.json

{
    "test" : "Hello! %(job), %(name)s, (function_name)"
}

test01.py

import json

a = 'test'
name = 'John'
job = 'student'

def function_name(message):
    print(message)

with open('json01.json') as json_file:
    json_dict = json.load(json_file)

if a in json_dict:
    print(json_dict[a] %locals())
#This works if there's only variables in the value
#but I don't know how to call functions when the value is not only function's name but also variables..

是否有任何简单的方法来打印它们的值? 还是有其他方法可以完成这项工作?

抱歉解释不佳,谢谢!

【问题讨论】:

  • 尝试使用eval()
  • 哦,是的,我使用了 eval() 并且它有效,但我想在不使用 eval() 的情况下执行此操作.. 有什么想法吗?
  • 嗯,从字符串中调用变量,我只能拿出eval()函数。
  • hmm.. 如果没有eval()..,可能无法从字符串中同时调用变量和函数?
  • 你想向函数传递参数吗?

标签: python json python-3.x dictionary


【解决方案1】:

您可以使用正则表达式定义自己的函数替换器。我在这里定义了一个示例语法:Hello, !(function_name) 其中function_name 是被调用函数的名称。

使用正则表达式,我们找到函数调用的所有出现并尝试 对它们一一进行评估。如果成功,我们将函数的名称替换为返回值。

import re

def runfunctions(string):
    # find all functions defined with our syntax
    funcs = re.findall(r'!\((.*?)\)', string)
    result = string
    # iterate through found functions
    for func in funcs:
        try:
            # try to evaluate with globals()[func]() and replace function call
            # with return value
            result = re.sub(r'!\(' + func + r'\)', globals()[func](), result)
        except (KeyError, TypeError) as e:
            # if func is not callable or does not exist catch error
            print("Error while evaluating functions in string:", e)
    # return final result
    return result

注意:我用globals 代替locals 否则找不到函数。

你可以这样使用它:

if a in json_dict:
    replaced_vars = json_dict[a] % locals()
    replaced_funcs = runfunctions(replaced_vars)
    print(replaced_funcs)

【讨论】:

  • 如果你想向函数传递参数,你必须明确你想传递哪些参数。这可能需要额外的语法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
  • 2017-11-14
相关资源
最近更新 更多