在 python 中使用带有 unicode 文本的 jsbeautifier 时出错

Error using jsbeautifier in python with unicode text

我用下面的代码美化一个js文件(用jsbeautifier模块)使用python (3.4)

import jsbeautifier

def write_file(output, fn):
    file = open(fn, "w")
    file.write(output)
    file.close()

def beautify_file():
    res = jsbeautifier.beautify_file("myfile.js")
    write_file(res, "myfile-exp.js")
    print("beautify_file done")

def main():
    beautify_file()
    print("done")
    pass

if __name__ == '__main__':
    main()

文件包含以下内容:

function MyFunc(){
  return {Language:"Мова",Theme:"ТÑма"};
}

当我 运行 python 代码时,出现以下错误:

'charmap' codec can't decode byte 0x90 in position 43: character maps to <undefined>

有人可以指导我如何使用美化器处理 unicode/utf-8 字符集吗?

谢谢

如果没有完整的堆栈跟踪就很难判断,但看起来 jsbeautify 并不完全支持 Unicode。

尝试以下方法之一:

  1. 将js文件解码为Unicode:

    with open("myfile.js", "r", encoding="UTF-8") as myfile:
        input_string = myfile.read()
        res = jsbeautifier.beautify(input_string)
    

    或者,如果失败

  2. 以二进制方式打开文件:

    with open("myfile.js", "rb") as myfile:
        input_string = myfile.read()
        res = jsbeautifier.beautify(input_string)
    

此外,您在写作时可能会运行遇到问题。您确实需要在输出文件上设置编码:

file = open(fn, "w", encoding="utf-8")