knowledge-vault/sources/references/零散旧笔记/test.py

25 lines
942 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 我想做一个文本输出的类,把我的提示词转成文本输出,中间有一部分会使用到我从系统里取得的数据
# 这个类的名字叫做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())