Python 3.x 在Python中连接文本文件时出现UnicodeEncodeError
我是python初学者。 我正在尝试将所有8个文本文件中的文本添加(连接)到一个文本文件中,以生成一个语料库。 然而,我得到了错误 UnicodeDecodeError:“charmap”编解码器无法解码位置7311中的字节0x9d:字符映射到Python 3.x 在Python中连接文本文件时出现UnicodeEncodeError,python-3.x,file-io,text-files,python-unicode,corpus,Python 3.x,File Io,Text Files,Python Unicode,Corpus,我是python初学者。 我正在尝试将所有8个文本文件中的文本添加(连接)到一个文本文件中,以生成一个语料库。 然而,我得到了错误 UnicodeDecodeError:“charmap”编解码器无法解码位置7311中的字节0x9d:字符映射到 filenames = glob2.glob('Final_Corpus_SOAs/*.txt') # list of all .txt files in the directory print(filenames) 输出: ['Final\u
filenames = glob2.glob('Final_Corpus_SOAs/*.txt') # list of all .txt files in the directory
print(filenames)
输出:
['Final\u Corpus\u SOAs\\1.txt'、'Final\u Corpus\u SOAs\\2.txt'、'Final\u Corpus\u SOAs\\2018 SOA Muir.txt'、'Final\u Corpus\u SOAs\\3.txt'、'Final\u Corpus\u SOAs\\4.txt'、'Final\u Corpus\u SOAs\\5.txt'、'Final\u Corpus\u SOAs\\6.txt'、'Final\u Corpus\u SOAs\\7.txt'、'Final\u Corpus\u SOAs\\8.txt']
with open('output.txt', 'w',encoding="utf-8") as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
输出:
UnicodeDecodeError:“charmap”编解码器无法解码位置7311中的字节0x9d:字符映射到未定义
谢谢您的帮助。您应该在打开文件时指定编码类型。更多信息请参见此。因为这里已经回答了这个问题 将
encoding=“utf8”
添加到您的代码中,如下所示
with open('output.txt', 'w', encoding="utf8") as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
如果您确定编码,则应在打开文件进行读写时声明编码:
encoding = 'utf8' # or 'latin1' or 'cp1252' or...
with open('output.txt', 'w',encoding=encoding) as outfile:
for fname in filenames:
with open(fname, encoding=encoding) as infile:
for line in infile:
outfile.write(line)
如果您不确定或不想被编码所困扰,可以通过将文件读写为二进制文件,在字节级别复制文件:
with open('output.txt', 'wb') as outfile:
for fname in filenames:
with open(fname, 'rb') as infile:
for line in infile:
outfile.write(line)
谢谢你的邀请answer@Sabesh.I已经尝试了encoding=“utf-8”以及errors=“ignore”。它仍然显示错误“UnicodeDecodeError:'charmap'编解码器无法解码7311位置的字节0x9d:字符映射到”。