python - 源到源转换

我想在 python 中使用 string 操作将 input.js 转换为 output.js

这是 input.js

let k=document.createElement("div");
k.innerHTML='<style>\n    .wrapper {\n      opacity: 0;\n      transition: visibility 0s, opacity 0.25s ease-in;\n    }\n\n    .overlay {\n      height: 100%;\n      position: fixed;\n      top: 0;\n      right: 0;\n    }\n\n    button {\n      cursor: pointer;\n      font-size: 1.25rem;\n    }\n  </style>\n  <div class="wrapper">\n  <div class="overlay"></div>\n    <div>\n      <button class="close">️x</button>\n      <h1 id="title">Hello world</h1>\n      <div id="content" class="content">\n        <p>This is content outside of the shadow DOM</p>\n      </div>\n    </div>\n  </div>';

这是 output.js

let k=document.createElement("div");
k.innerHTML=`<style>
    .wrapper {
      opacity: 0;
      transition: visibility 0s, opacity 0.25s ease-in;
    }

    .overlay {
      height: 100%;
      position: fixed;
      top: 0;
      right: 0;
    }

    button {
      cursor: pointer;
      font-size: 1.25rem;
    }
  </style>
  <div class="wrapper">
  <div class="overlay"></div>
    <div>
      <button class="close">️x</button>
      <h1 id="title">Hello world</h1>
      <div id="content" class="content">
        <p>This is content outside of the shadow DOM</p>
      </div>
    </div>
  </div>`;

获取 output.js 的所有信息都存在于 input.js 中。没有信息丢失。

下面不起作用

import html
import sys
import io


def sprint(*args, end='', **kwargs):
    sio = io.StringIO()
    print(*args, **kwargs, end=end, file=sio)
    return sio.getvalue()

with open('input.js') as f, open('output.js', 'w') as of:
    for line in f:
        if 'innerHTML' in line:
            arr = line.split("=")
            nline = arr[0]+"=`"+sprint(html.unescape(arr[1].strip(" '\"")))+"`\n"
            of.write(nline)
            continue
        of.write(line)

我想从缩小的 javascript 文件中漂亮地打印我的 innerHTML strings 。在 python.

回答1

这可以使用 string 编解码器来完成。对文件使用 utf8 编码,并将输入转换为字节。然后使用 'unidecode_escape' 解码,转义 unicode 字符,例如换行符“\n”,并输出到文件 output.js。查看 https://stackoverflow.com/questions/4020539/process-escape-sequences-in-a-string-in-python 中的 string 中的进程转义序列以获得进一步的解释:

with open('input.js', 'r', encoding="utf8") as f,
     open('output.js', 'w', encoding="utf8") as of:
    for line in f:
        of.write(bytes(line, "utf8").decode('unicode_escape'))

相似文章

maui - 未能更新广告清单

我在maui上开发blazor,vs202217.1preview2。然后它停止工作,在powershell上运行maui-check,我收到一些错误,我尝试修复它们,然后我得到以下信息:未能更新广告...

graph-theory - K-连接反射、对称、传递

我必须证明以下几点:在有向图中,如果从向量x到y有k个不同的路径(不使用相同的边),并且从向量y到x有k个不同的路径(不使用相同的边),我们将其符号化像这样:x≡𝑘y我们称它们为k连通向量。我必须证...

随机推荐

最新文章