python - Python字符串替换截断新字符串
问题描述
我有以下 HTML 文档
<!DOCTYPE HTML>
<html>
<head>
<link href="style.css" rel="stylesheet">
<script src="firstScript.js"></script>
<script src="secondScript.js"></script>
...
</head>
<body onload='function()' ..."></body>
</html>
这对开发非常有用,但最后我需要将所有这些脚本和 .css 文件直接放入我的 html 文档中,而不是引用它们。为了实现这一点,我在 python 中编写了一个小构建脚本,以将包含文件名的每一行替换为包含在适当 html 标记中的该文件的内容。这里有一个小片段来展示 javascript 文件会发生什么。
FILES = [ "firstScript.js", "secondScript.js", ... ]
OUTPUT = "path/to/build.html"
for f in FILES:
scriptFile = open(f, "r")
scriptDAT = "<script>\n"+scriptFile.read()+"</script>"
scriptFile.close()
with fileinput.FileInput(OUTPUT, inplace=True) as file:
for line in file:
if line.find(f) >= 0: line = line.replace(line, scriptDAT)
print(line)
这主要是有效的,但有时 line.replace 会在 scriptDAT 中写入所有内容,除了</script>
最后的标签。例如,如果 firstScript.js 包含
function helloWorld() {
console.log(helloWorld);
}
然后这个脚本在替换第一行之后可能会产生 html 文件
<!DOCTYPE HTML>
<html>
<head>
<link href="style.css" rel="stylesheet">
<script>
function helloWorld() {
console.log("Hello World!");
}
<script src="secondScript.js"></script>
...
</head>
<body onload='function()' ..."></body>
</html>
忽略字符串末尾的line.replace(line, scripDAT)
结束标记。真正奇怪的是,这种行为有时只会发生。当 python 脚本替换 secondScript.js 时,它可能包含结束标记。有谁知道为什么替换方法会这样?
解决方案
推荐阅读
- python-3.x - 我的列表理解不正确吗?
- javascript - aws cognito 电子邮件更改
- c - DISLIN 不适用于代码块
- angular - 如何在不通过 [formControl] 嵌套表单标签的情况下对输入进行自定义验证?
- javascript - 等到所有 http GET 请求完成后再登录到 JS 中的控制台
- google-sheets - 在公式中使用一个单元格的值来查找特定的单元格
- ruby - Ruby 有“等于或”运算符吗?
- sql - Oracle SQL 数据修改
- python - 如果字典列表具有相同的特定值,则用另一字典列表的值更新一个字典列表
- c# - 使用复合设计模式时的 Unity-NullReferenceException