gpt4 book ai didi

python - Python 中的 CL-WHO : clever or just stupid?

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:21 25 4
gpt4 key购买 nike

我不知道这是聪明还是愚蠢。我喜欢 CL-WHO,也喜欢 Python,所以我一直在想办法将两者结合起来。我想说的是:

tag("html",
lst(
tag("head"),
tag("body",
lst(
tag("h1", "This is the headline"),
tag("p", "This is the article"),
tag("p",
tag("a", "Click here for more", ["href", "http://nowhere.com"]))))))

并让它评估为:

<html>
<head>
</head>
<body>
<h1>This is the headline</h1>
<p>This is the article</p>
<p>
<a href="http://nowhere.com">Click here for more</a>
</p>
</body>
</html>

看起来就像 CL-WHO 但使用函数符号而不是 s 表达式。所以我开始使用这个标签生成函数:

def tag(name, inner="", attribs=[], close=True):
ret = []
ret.append('<' + name)
while attribs.__len__() > 0:
ret.append(' %s="%s"' % (attribs.pop(0),attribs.pop(0)))
ret.append(">")
if type(inner).__name__ == 'list':
ret.extend(inner)
else:
ret.append(inner)
if close:
ret.append('</%s>' % name)
return "".join(ret)

inner 可以是一个列表,而列表的方括号在所有 Lispy 代码中都很丑陋,所以我想要一个根据其参数生成列表的函数:

def lst(*args):
return [x for x in args]

为了促进条件代码生成,您需要一个 if 语句,它是一个计算两个结果之一的函数,就像在 Lisp 中一样,因此您可以嵌套它。命令式流程控制风格的 if 不行。

def fif(cond, a, b):
if cond:
return a
else:
return b

中提琴。现在您可以像这样生成示例页面:

def gen(x):
"""Sample function demonstratine conditional HTML generation. Looks just like CL-WHO!"""
return tag("html",
lst(
tag("head"),
tag("body",
lst(
fif(x == 1, tag("h1", "This is the headline"), tag("h1", "No, THIS is the headline")),
tag("p", "This is the article"),
tag("p",
tag("a", "Click here for more", ["href", "http://nowhere.com"]))))))

print gen(1)

开始崩溃的地方是循环。任何循环的东西都必须被提取到一个单独的函数中。那你觉得怎么样?有趣还是愚蠢?试一试并告诉我你的想法。

最佳答案

你应该对每个文本节点、属性值等进行 html 转义,否则 html 注入(inject)和 XSS 会咬你。

除了功能齐全的模板系统(mako、genhi、chameleon、jinja 等)之外,与您所做的更相似的库可能是 lxml

>>> from lxml.html.builder import HTML, HEAD, BODY, H1, P, A
>>> from lxml.html import tostring
>>>
>>> h = HTML(
... HEAD(
... BODY(
... H1('This is the headline'),
... P('This is the article'),
... P(
... A('Click here for more', href='http://nowhere.com')))))
>>> print tostring(h, pretty_print=True)
<html><head><body>
<h1>This is the headline</h1>
<p>This is the article</p>
<p><a href="http://nowhere.com">Click here for more</a></p>
</body></head></html>

你可以使用三元运算符

H1("This is the headline" if x==1 else "No, THIS is the headline")

关于python - Python 中的 CL-WHO : clever or just stupid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5680697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com