25 lines
942 B
Python
25 lines
942 B
Python
# 我想做一个文本输出的类,把我的提示词转成文本输出,中间有一部分会使用到我从系统里取得的数据
|
||
# 这个类的名字叫做TextOutput,入参是一个字符串,是提示词的模板,另一个入参是Json格式的数据,是我从系统里取得的数据
|
||
# 返回值是一个字符串
|
||
# 2018-10-15
|
||
|
||
import json
|
||
|
||
class TextOutput:
|
||
def __init__(self, template: str, data: str):
|
||
self.template = template
|
||
self.data = json.loads(data)
|
||
|
||
def generate_output(self) -> str:
|
||
output = self.template
|
||
for key, value in self.data.items():
|
||
placeholder = f'{{{{{key}}}}}'
|
||
output = output.replace(placeholder, str(value))
|
||
return output
|
||
|
||
# 示例用法
|
||
template = "Hello, my name is {{name}} and I am {{age}} years old."
|
||
data = '{"name": "Alice", "age": 30}'
|
||
text_output = TextOutput(template, data)
|
||
print(text_output.generate_output())
|