我希望在python中使用字符串操作将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字符串。在python中有没有一种干净的方法可以做到这一点。
发布于 2022-05-14 10:13:00
这可以使用字符串编解码器来完成。对文件使用utf8 8编码,并将输入转换为字节。然后使用‘unidecode_ and’解码,以转义unicode字符,例如新行"\n",并输出到文件output.js。有关进一步解释,请参阅Process escape sequences in a string in Python:
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'))
https://stackoverflow.com/questions/72239129
复制相似问题