我有一些动态生成并存储在文本文件中的 Python 代码。它基本上由各种变量组成,例如存储数据的列表和字符串。该信息被提供给一个类来实例化不同的对象。如何将文本文件中的数据输入到课堂中?
这是我的课:
class SomethingA(Else):
def construct(self):
// feed_data_a_here
self.call_method()
class SomethingB(Else):
def construct(self):
// feed_data_b_here
self.call_method()
以下是
text_a
文件中的一些示例内容。正如您所看到的,这是一些有效的 Python 代码,我需要将其直接输入到对象中。调用 call_method()
取决于此输出数据。
self.height = 12
self.id = 463934
self.name = 'object_a'
有没有办法将这些数据加载到类中,而无需从文本文件中手动复制和粘贴所有数据?
谢谢。
我可能会为你的文件编写一个解析器来删除“self”。在开头并将变量添加到字典中:
import re
# You could use more apprpriate regex depending on expected var names
regex = 'self\.(?P<var_name>\D+\d*) = (?P<var_value>.*)'
attributes= dict()
with open(path) as file:
for line in file:
search = re.search(regex, line)
var_name = search.group(var_name)
var_value = search.group(var_value).strip() # remove accidentalwhite spaces
attributes[var_name] = var_value
foo = classA(**attributes)
如果您使用我建议的代码,字典中的所有项目都将是字符串类型。也许你可以尝试:
eval()
,由@Welgriv 提议,但稍作修改:eval(f'attributes[{var_name}] = {var_value}')
json
:import json
x = '12'
y = '[1, 2, 3]'
z = '{"A": 50.0, "B": 60.0}'
attributes = {}
for i, v in enumerate([x, y, z]):
attributes[f'var{i+1}'] = json.loads(v)
print(attributes)
# Prints
# {'var1': 12, 'var2': [1, 2, 3], 'var3': {'A': 50.0, 'B': 60.0}}
您可能会寻找 eval() 函数。它评估并尝试将 python 表达式作为文本执行。例如:
eval('print("All your base are belong to us")')
将打印该句子。在您的情况下,您应该打开文本文件,然后对其进行评估。
eval()
函数存在一些安全问题,因为用户可能会执行任何代码。