【问题标题】:unicode not printing on when imported from text file python从文本文件python导入时,unicode不打印
【发布时间】:2021-09-13 19:17:02
【问题描述】:

我正在从 python 读取文本文件,当它打印 Unicode 时,它​​不打印符号。

输入.txt:

hello world
\u00a9

代码:

from pathlib import Path 
with open('input.txt','r') as file:
    txt = Path('input.txt').read_text()
    print(txt)

输出:

hello world 
\u00a9

预期输出:

hello world
°

【问题讨论】:

  • 请编辑您的问题并进行一些格式化。可读性不是很好。但是可以看到,您的文件不包含°。您的文件包含文本 \u00a9 并且已打印。作为文本文件中的字符的字符\u00a9 与程序本身中的字符串定义"\u00a9" 之间存在差异。检查print("\u00a9")print(r"\u00a9")

标签: python text unicode python-unicode


【解决方案1】:

打印的数据正是文件中的内容。要翻译 Unicode 转义,您需要将其指定为编码。原代码也是混合文件读取方式,所以这里有两个版本:

with open('input.txt',encoding='unicode-escape') as f:
    txt = f.read()
print(txt)
from pathlib import Path
txt = Path('input.txt').read_text(encoding='unicode-escape')
print(txt)

输出(两个版本):

hello world
©

请注意\u00a9 是版权符号,而不是度数符号。度数符号是\u00b0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多