更新:如果输出文件是 yaml 文档,那么您可以忽略\u0163
它。Unicode 转义在 yaml 文档中有效。
#!/usr/bin/env python3
import json
# json produces a subset of yaml
print(json.dumps('pe toţi mai')) # -> "pe to\u0163i mai"
print(json.dumps('pe toţi mai', ensure_ascii=False)) # -> "pe toţi mai"
注意:\u
在最后一种情况下没有。这两行代表相同的 Python 字符串。
yaml.dump()
有类似的选项:allow_unicode
. 将其设置True
为避免 Unicode 转义。
网址是正确的。你不需要对它做任何事情:
#!/usr/bin/env python3
from urllib.parse import unquote
url = "pe%20to%C5%A3i%20mai"
text = unquote(url)
with open('some_file', 'w', encoding='utf-8') as file:
def p(line):
print(line, file=file) # write line to file
p(text) # -> pe toţi mai
p(repr(text)) # -> 'pe toţi mai'
p(ascii(text)) # -> 'pe to\u0163i mai'
p("pe to\u0163i mai") # -> pe toţi mai
p(r"pe to\u0163i mai") # -> pe to\u0163i mai
#NOTE: r'' prefix
该\u0163
序列可能由字符编码错误处理程序引入:
with open('some_other_file', 'wb') as file: # write bytes
file.write(text.encode('ascii', 'backslashreplace')) # -> pe to\u0163i mai
或者:
with open('another', 'w', encoding='ascii', errors='backslashreplace') as file:
file.write(text) # -> pe to\u0163i mai
更多示例:
# introduce some more \u escapes
b = r"pe to\u0163i mai ţţţ".encode('ascii', 'backslashreplace') # bytes
print(b.decode('ascii')) # -> pe to\u0163i mai \u0163\u0163\u0163
# remove unicode escapes
print(b.decode('unicode-escape')) # -> pe toţi mai ţţţ