如何在Python3中基于Unicode代码点将汉字写入文件

问题描述

我正在尝试根据unicode.org/Public/zipped/13.0.0/Unihan.zip文本文件中的Unicode代码点将汉字写入CSV文件。例如,一个示例字符是U + 9109。

在下面的示例中,我可以通过对值进行硬编码来获得正确的输出(第8行),但是对于尝试从代码生成字节的每个排列(第14-16行),都将其弄错。

我正在基于Debian的Linux发行版中的Python 3.8.3中运行它。

最小工作(中断)示例:

  1 #!/usr/bin/env python3
  2 
  3 def main():
  4 
  5     output = open("test.csv","wb")
  6 
  7     # Hardcoded values work just fine
  8     output.write('\u9109'.encode("utf-8"))
  9 
 10     # Comma separation
 11     output.write(','.encode("utf-8"))
 12 
 13     # Problem is here
 14     codepoint = '9109'
 15     u_str = '\\' + 'u' + codepoint
 16     output.write(u_str.encode("utf-8"))
 17 
 18     # End with newline
 19     output.write('\n'.encode("utf-8"))
 20 
 21     output.close()
 22 
 23 if __name__ == "__main__":
 24     main()

执行和查看结果:

example $
example $./test.py 
example $
example $cat test.csv 
鄉,\u9109
example $


预期输出如下所示(逗号两侧出现汉字):

example $
example $./test.py 
example $cat test.csv 
鄉,鄉
example $

解决方法

axios.interceptors.request.use((config) => { if (store.getters.token) { config.headers['x-token'] = getToken(); } return config; }); axios.interceptors.response.use( response=>{ const res = response.data if (res.code != 200) { Message({ message: res.data || "Error",type: 'error' }) if(res.code == 401) { MessageBox.confirm(res.data,'重新登录',{ confirmButtonText: '确定',type: 'warning' }).then(() => { store.dispatch('user/logout') window.location.replace('/login') }) } return res } else { return res } }) 用于在Python 3中将整数转换为代码点。您的代码可以使用:

chr

但是,如果您在output.write(chr(0x9109).encode("utf-8")) 中指定编码,而不是使用二进制模式,则不必手动编码所有内容。 open也会为您处理换行符。

print

输出:

with open("test.txt",'w',encoding='utf-8') as output:
    for i in range(0x4e00,0x4e10):
        print(f'U+{i:04X} {chr(i)}',file=output)