Python: 将变音符作为转义字符序列写入文件

Python: Write to file diacritical marks as escape character sequence

我从输入文件中读取文本行,剪切后我有字符串:

-pokaż wszystko-
–ყველას გამოჩენა–

而且我必须像这样写入其他文件:

-poka7C wszystko-
 13E7D5D4DAD0E1 D2D0DBDDE9D4DCD013

我的 python 脚本开始于:

file_input = open('input.txt', 'r', encoding='utf-8')
file_output = open('output.txt', 'w', encoding='utf-8')

不幸的是,写入文件不是它所期望的。

我知道为什么我必须更改它,但无法弄清楚转换:

Diacritic marks saved in UTF-8 ("-pokaż wszystko-"), it works correctly only if NLS_LANG = AMERICAN_AMERICA.AL32UTF8

If the output file has diacritics saved in escaping form ("-poka7C wszystko-"), the script works correctly for any NLS_LANG settings

Python 3.6解决方案...格式化ASCII范围外的字符:

#coding:utf8
s = ['-pokaż wszystko-','–ყველას გამოჩენა–']

def convert(s):
    return ''.join(x if ord(x) < 128 else f'\{ord(x):04X}' for x in s)

for t in s:
    print(convert(t))

输出:

-poka7C wszystko-
13E7D5D4DAD0E1 D2D0DBDDE9D4DCD013

注意:我不知道您是否或如何处理基本多语言平面(BMP、> U+FFFF)之外的 Unicode 字符,但此代码可能无法处理它们。需要有关转义序列要求的更多信息。