如何将字符串中的非ascii(ascii>;127)字符编码为UTF-16格式,以便“é”变为“\u00e9”,“Ř”变为“\u0158”。我所做的是将字符转换成十六进制,并将前两个字符替换为\u00(对于UTF-16)。但这没用…给我垃圾值。请帮我找一个正确的算法。在
以下是我写的,但它不能正确转换:
f = open ("input.txt","r")
data = f.read()
x=list(data)
i=0
for element in x:
if ord(element)>127:
y=hex(ord(x[i]))
y=y[2:]
y='\u00'+y
x[i]=y
i=i+1
data=''.join(x)
t= open("output.txt","w")
t.write(data)
f.close()
t.close()
使用内置的^{} method of strings :
以二进制模式打开文件
如果不起作用,试试内置的编解码器
^{pr2}$@TokenMacGuy已将此答案发布到the old question which you've deleted。你仍然可以看到这个问题,因为这个问题已经被删除了
所以你想从unicode转换成ascii表示法,其中非ascii码位被“转义”?如果是的话,那么:
顺便说一下,这个算法是而不是utf-16;请不要那么叫它;它是ASCII!UTF-16如下所示:
^{pr2}$注意:您没有指定此示例是在python2.7中,而不是python3;如果您需要,请将其添加到您的问题中
我不确定这是否对你有帮助。或者,@TokenMacGuy自己会编辑这个答案,使它更有帮助。在
相关问题 更多 >
编程相关推荐