首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >源到源转换

源到源转换
EN

Stack Overflow用户
提问于 2022-05-14 09:59:10
回答 1查看 49关注 0票数 0

我希望在python中使用字符串操作将input.js转换为output.js

这是input.js

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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中。信息没有丢失。

以下不起作用

代码语言:javascript
运行
复制
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中有没有一种干净的方法可以做到这一点。

EN

回答 1

Stack Overflow用户

发布于 2022-05-14 10:13:00

这可以使用字符串编解码器来完成。对文件使用utf8 8编码,并将输入转换为字节。然后使用‘unidecode_ and’解码,以转义unicode字符,例如新行"\n",并输出到文件output.js。有关进一步解释,请参阅Process escape sequences in a string in Python

代码语言:javascript
运行
复制
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'))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72239129

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档