0

私はプログラミングにかなり慣れていません。文字列 '{{name}} is in {{course}}' を受け取り、{{name}} と {{course}} をそれぞれのキー値に置き換える 2 つのクラス メソッドを作成しようとしています。辞書。そう:

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}}」の場合にアサーション エラーが発生する理由がわかりません. それ以外の場合は、はるかに単純な方法が堪能になります。

4

2 に答える 2

1

マリウスはあなたの質問への回答に私を打ち負かしましたが、私は (ほぼ) 同じことを行うためのより簡単な方法を指摘したかっただけです. もちろん、単に学ぼうとしているだけなら、通常は難しい方法よりも優れています。

vars = {
    'name': 'Jane',
    'course': 'CS 1410'
    }

out = '{name} is in {course}'.format(**vars)
print out
于 2013-09-27T00:43:00.187 に答える