首页 > 解决方案 > 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 时,它可能包含结束标记。有谁知道为什么替换方法会这样?

标签: pythonhtmlcssstring

解决方案


推荐阅读