Python 从文件中读取中文文本并将其打印到shell
我正在尝试制作一个程序,从一个.txt文件中读取一行汉字并将它们打印到Python shell(IDLE?) 我遇到的问题是试图对utf-8中的字符进行编码和解码,使其能够以中文打印 到目前为止,我有:Python 从文件中读取中文文本并将其打印到shell,python,utf-8,foreign-keys,decode,encode,Python,Utf 8,Foreign Keys,Decode,Encode,我正在尝试制作一个程序,从一个.txt文件中读取一行汉字并将它们打印到Python shell(IDLE?) 我遇到的问题是试图对utf-8中的字符进行编码和解码,使其能够以中文打印 到目前为止,我有: file_name = input("Enter the core name of the text you wish to analyze:")+'.txt' file = open(file_name, encoding="utf8") file = file.read().
file_name = input("Enter the core name of the text you wish to analyze:")+'.txt'
file = open(file_name, encoding="utf8")
file = file.read().decode('utf-8').split()
print(file)
但是,每次我运行代码时,都会不断收到提示,提示出现此错误
file = file.read().decode('utf-8').split()
AttributeError: 'str' object has no attribute 'decode'
现在,我不完全确定这意味着什么,因为我对编程语言还不熟悉,所以我想知道是否可以从你们那里得到一些提示。非常感谢 从您的错误消息中,我怀疑
.read()
的输出已经是一个字符串(更准确地说,如果您使用的是Python 3
,则为unicode字符点)
您是否在没有调用.decode()
的情况下尝试了它
为了更好地处理文件,请使用带上下文的
,因为这样可以确保退出块后文件将正确关闭。
此外,您还可以使用for line in f
语句对文件中的行进行迭代
file_name = input("Enter the core name of the text you wish to analyze:")
with open(file_name + '.txt', encoding='utf8') as f:
for line in f:
line = line.strip() # removes new lines or spaces at the start/end
print(line)
在Python 3中读取以这种方式打开的文件时:
文件=打开(文件名,编码=“utf8”)
您告诉它该文件是用UTF-8编码的,Python将自动对其进行解码file.read()。只需执行以下操作(不要覆盖文件
…这是您的文件句柄):
data = file.read().split()