我对编程相当陌生。我正在尝试编写两个将采用字符串的类方法, '{{name}} is in {{course}}' ,并将 {{name}} 和 {{course}} 替换为它们各自的 Key 值字典。所以:
t = Template()
vars = {
'name': 'Jane',
'course': 'CS 1410'
}
out = t.process('{{name}} is in {{course}}', vars)
print 'out is: [' + out + ']'
将打印:
Jane is in CS 1410
我的代码如下:
class Template:
def processVariable(self, template, data):
print template
assert(template.startswith('{{'))
start = template.find("{{")
end = template.find("}}")
out = template[start+2:end]
assert(out != None)
assert(out in data)
return data[out]
def process(self, template, data):
output = ""
check = True
while check == True:
start = template.find("{{")
end = template.find("}}")
output += template[:start]
output += self.processVariable(template[start:end+2], data)
template = template.replace(template[:end+2], "")
for i in template:
if i == "}}":
check = True
output += template
return output
t = Template()
vars = {
'name': 'Jane',
'course': 'CS 1410'
}
out = t.process('{{name}} is in {{course}}', vars)
print 'out is: [' + out + ']'
当我运行代码时,我得到以下输出:
{{name}}
{{course}}
Traceback (most recent call last):
File "C:some/filepath/name.py", line 46, in <module>
out = t.process('{{name}} is in {{course}}', vars)
File "C:some/filepath/name.py", line 28, in process
output += self.processVariable(template[start:end+2], data)
File "C:some/filepath/name.py", line 8, in processVariable
assert(template.startswith('{{'))
AssertionError
我只是不明白如果模板是'{{course}}',我为什么会收到断言错误编辑:以这种方式编写代码的目的是引入任何字典和字符串,以便我可以创建一个简单的社交网络. 否则,更简单的方法将是熟练的。