如何在没有.readlines()的情况下读取.txt文件/将UTF8换行符替换为\n?

2024-09-29 23:18:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个.txt文件中有一些人工智能生成的废话,如下所示:

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()生成的列表,但是事实上网页.py需要把它放到render.index()里,事情就复杂了。你知道吗

我试过的

我的第一个想法是在生成menenius.txt文件用\n替换不可见UTF-8换行符的每个实例。因为.read()将整个.txt文件作为一个字符串提供给您,所以我认为这样做是可行的,但是这样做:

from_text = open("menenius.txt", "r").read()
from_text.replace(0x0A, "\n")

获取此错误,引用带有.replace()的行:

TypeError: expected a character buffer object

我在google上搜索过,但没有一个看起来非常适用或者非常清楚。我刚开始用Python,我已经用它绕了几个小时了,所以我觉得这里有一些非常明显的东西,我不知道。你知道吗


如前所述,我也尝试返回.readlines()生成的列表,但这会占用大量内存,而且我不确定如何将输出适配到render.index()。你知道吗

编辑:解决方案

所以下面的答案是可行的,但在我做了改变之后,我仍然有同样的问题。ShadowRanger的“我假设你的渲染器正在发送HTML”让我思考,我打开localhost并进入web检查器,查看所有文本都在它的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发现:

As you can see, the templates look a lot like Python files except for the def with statement at the top (saying what the template gets called with) and the $s placed in front of any code. Currently, template.py requires the $def statement to be the first line of the file. Also, note that web.py automatically escapes any variables used here, so that if for some reason name is set to a value containing some HTML, it will get properly escaped and appear as plain text. If you want to turn this off, write $:name instead of $name.

我将$content改为$:content,突然间文本被呈现为HTML而不是字符串。你知道吗


Tags: 文件ofthetotextpytxtweb
1条回答
网友
1楼 · 发布于 2024-09-29 23:18:43

您的文件已经包含换行符('\x0a''\n'产生的完全相同字符的转义符)。我假设您的呈现器正在发送HTML,而HTML并不关心文本中的换行符(在pre块之外,以及其他样式类似的块)。你知道吗

因此,要么将数据包装在pre块中,要么将'\n'替换为<br>标记(这就是HTML如何说“不,真的,我想要换行符”),例如:

from_text = from_text.replace("\n", "<br>\n")

保留换行符对查看源代码的人来说可能很方便,所以我用<br>标记和换行符进行了替换(Python不会在替换中替换,所以不要因为换行符是替换的一部分就担心无限替换)。你知道吗

相关问题 更多 >

    热门问题