直接改后缀无法使txt变为可用html,需注入html结构、转义特殊字符并处理换行空格;python用html.escape()和标签最简方案适合干净单页生成。
直接改文件后缀不会让 txt 变成可用的 html,浏览器打开还是纯文本——真正的转换需要注入 html 结构、转义特殊字符,并处理换行和空格等渲染逻辑。
用 Python open() + 字符串拼接最简单
适合内容干净、无用户输入、只求快速生成单页 HTML 的场景。核心是把原始文本包进 ,并用 <pre class="brush:php;toolbar:false;"></code> 保持格式。</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/2226" title="图酷AI"><img
src="https://img.php.cn/upload/ai_manual/000/000/000/175680384921471.png" alt="图酷AI" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/2226" title="图酷AI">图酷AI</a>
<p>下载即用!可以免费使用的AI图像处理工具,致力于为用户提供最先进的AI图像处理技术,让图像编辑变得简单高效。</p>
</div>
<a href="/ai/2226" title="图酷AI" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>
<ul>
<li>必须对 <code><</code>、<code>></code>、<code>&</code> 做转义,否则文本里的 HTML 标签会被浏览器解析(比如 <code>if (a < b)</code> 会出错)</li>
<li><code><pre class="brush:php;toolbar:false;"></code> 保留换行和空格,但默认字体小、无缩进;加 <code>style="white-space: pre-wrap;"</code> 更友好</li>
<li>别用 <code>str.replace()</code> 手动转义,优先用 <code>html.escape()</code>(Python 3.2+)</li>
</ul>
<pre class="brush:php;toolbar:false;">import html
with open("input.txt") as f:
text = f.read()
html_content = f"<!DOCTYPE html><html><body><pre class="brush:php;toolbar:false;" style=\"white-space: pre-wrap;\">{html.escape(text)}</pre>









