【发布时间】:2019-05-22 23:58:35
【问题描述】:
我在一个 .txt 文件中有一些 AI 生成的废话,如下所示:
MENENIUS:
I have been they prayers of the reason,
And away to friends than the state pointer;
The words that shall can virtue to your head.
我有一些 Python 代码(使用 web.py),如下所示:
class index(object):
def GET(self):
text = open("menenius.txt", "r").read()
return render.index(text)
当我在 localhost 中查看时,它看起来像这样:
MENENIUS: I have been they prayers of the reason, And away to friends than the state pointer; The words that shall can virtue to your head.
Menenius 的小演讲实际上只是一个更大的 .txt 文件的剪辑,所以我不想使用.readlines(),因为遍历列表会占用大量内存。如果这不是问题,在普通脚本中,我可以只打印.readlines() 生成的列表,但是我正在使用 web.py 并且需要将其放入render.index() 使事情变得复杂.
我的尝试
我的第一个想法是在生成menenius.txt 的脚本中使用.replace() 方法,将不可见的UTF-8 换行符的每个实例替换为\n。由于.read() 将整个 .txt 文件作为单个字符串提供给您,因此我认为这样做可行,但这样做:
from_text = open("menenius.txt", "r").read()
from_text.replace(0x0A, "\n")
得到我这个错误,指的是.replace()的行:
TypeError: expected a character buffer object
我用谷歌搜索过,但似乎没有一个非常适用或非常清楚。我刚刚开始使用 Python,我已经在这个圈子里转了几个小时,所以我觉得这里有一些我不知道的非常明显的东西。
正如我所提到的,我也尝试过返回 .readlines() 生成的列表,但这会占用大量内存,而且我不确定如何将该输出放入 render.index() 中。
编辑:解决方案
所以下面的答案有效,但在我做出改变后,我仍然遇到同样的问题。 ShadowRanger 的“我假设您的渲染器正在发送 HTML”让我开始思考,我打开 localhost 并进入网络检查器,看到所有文本都在其 p 标记内的引号中,如下所示:
<p>
"MENENIUS: I have been they prayers of the reason, And away to friends than the state pointer; The words that shall can virtue to your head."
</p>
几个小时后,我意识到了一些事情,然后又回到了这个问题上。在内容被发送到的index.html 文件中,它看起来像这样:
<p>
$content
</p>
我有一个怀疑,再次检查了web.py intro tutorial,发现了这个:
如您所见,模板看起来很像 Python 文件,除了顶部的 def with 语句(说明调用模板的内容)和放在任何代码前面的 $s。目前,template.py 要求 $def 语句是文件的第一行。另外,请注意 web.py 会自动转义此处使用的任何变量,因此如果出于某种原因将 name 设置为包含某些 HTML 的值,它将被正确转义并显示为纯文本。如果你想关闭它,写 $:name 而不是 $name。
我将$content 更改为$:content,突然文本被呈现为HTML 而不是字符串。
【问题讨论】: