【问题标题】:I want to generate the unicode UTF-16 for a text file in python我想在 python 中为文本文件生成 unicode UTF-16
【发布时间】:2020-09-18 12:04:16
【问题描述】:

如图所示,我在一个文件中有一个普通文本,我想用 unicode 编写这样的文本

我有这段代码,但它没有做这项工作,它只是按原样编写文本,而我确实需要显示 utf-16 编码

with open(localOutputPath,'r') as infile:
        data = infile.read()
        #print(data)

    with open(localUtf16Path, 'w', encoding="utf-16") as outfile:
        outfile.write(data)

【问题讨论】:

  • 您右侧的示例不是 UTF-16。那是 Unicode 转义序列。
  • 你有那个脚本吗

标签: python character-encoding utf-16


【解决方案1】:

完全没用:

==> type .\SO\62111029.py
import io
localOutputPath = r'd:\bat\62111029input.txt'
localUtf16Path  = r'd:\bat\62111029output.txt'
data = []
with io.open(localOutputPath, mode="r", encoding="utf-8") as infile:
    with io.open(localUtf16Path, mode="w", encoding="utf-8") as outfile:
        for line in infile:
            data = ''.join(['\\u' + '{:04x}'.format(ord(letter))
                for letter in line.rstrip('\n')]).replace('\\u0020',' ')
            outfile.write(data + '\n')
==> 2>NUL del 62111029output.txt

==> type 62111029input.txt
September 1, 1939
1 Σεπτεμβρίου 1939
1 сентября 1939
1. září 1939
==> .\SO\62111029.py

==> type 62111029output.txt

\u0053\u0065\u0070\u0074\u0065\u006d\u0062\u0065\u0072 \u0031\u002c \u0031\u0039\u0033\u0039
\u0031 \u03a3\u03b5\u03c0\u03c4\u03b5\u03bc\u03b2\u03c1\u03af\u03bf\u03c5 \u0031\u0039\u0033\u0039
\u0031 \u0441\u0435\u043d\u0442\u044f\u0431\u0440\u044f \u0031\u0039\u0033\u0039
\u0031\u002e \u007a\u00e1\u0159\u00ed \u0031\u0039\u0033\u0039

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 2023-03-16
    • 2010-10-21
    • 2011-10-10
    相关资源
    最近更新 更多