Python3中如何根据unicode码位将汉字写入文件
How to write Chinese characters to file based on unicode code point in Python3
我正在尝试根据在 unicode 文本文件中找到的 Unicode 代码点将汉字写入 CSV 文件。org/Public/zipped/13.0.0/Unihan.zip。例如,一个示例字符是 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 $
chr
用于将整数转换为 Python 中的代码点 3. 您的代码可以使用:
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)
输出:
U+4E00 一
U+4E01 丁
U+4E02 丂
U+4E03 七
U+4E04 丄
U+4E05 丅
U+4E06 丆
U+4E07 万
U+4E08 丈
U+4E09 三
U+4E0A 上
U+4E0B 下
U+4E0C 丌
U+4E0D 不
U+4E0E 与
U+4E0F 丏
我正在尝试根据在 unicode 文本文件中找到的 Unicode 代码点将汉字写入 CSV 文件。org/Public/zipped/13.0.0/Unihan.zip。例如,一个示例字符是 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 $
chr
用于将整数转换为 Python 中的代码点 3. 您的代码可以使用:
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)
输出:
U+4E00 一
U+4E01 丁
U+4E02 丂
U+4E03 七
U+4E04 丄
U+4E05 丅
U+4E06 丆
U+4E07 万
U+4E08 丈
U+4E09 三
U+4E0A 上
U+4E0B 下
U+4E0C 丌
U+4E0D 不
U+4E0E 与
U+4E0F 丏