我试图读取文本文件,但它抛出了一个错误。
UnicodeEncodeError: 'UCS-2' codec can't encode characters in position 12416-12416: Non-BMP character not supported in Tk我也试图忽略它,但我没有工作。以下是代码:
with io.open('reviews1.txt', mode='r',encoding='utf-8') as myfile:
document1=myfile.read().replace('\n', '')
print(document1)发布于 2017-07-07 20:55:37
我可以在Python空闲环境 (Python version 3.5.1, Tk version 8.6.4, IDLE version 3.5.1)中再现错误。它似乎是Tk中的一个bug。但是,原始脚本在控制台(在我的例子中是cmd ):Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32上运行得很平稳。
我能看到的唯一方法是非常慢的:下面的注释脚本逐个字符复制整个文档字符,将所有文档字符从基本多语言平面中删除。
编辑:我找到了)解决方案(感谢马克·兰瑟姆)。不幸的是,这在Python中运行,但是Python控制台抱怨:
打印(‘.’.join(c如果c <= '\uffff‘else’.‘.join(chr(X) for x in struct.unpack( . '>2H',c.encode(’utf-16 if‘))在document1中)).追溯(最近一次调用):文件"",第2行,文件"C:\Python\Python35\lib\site-packages\win_unicode_console\streams.py",第179行,写入返回self.base.write(s) UnicodeEncodeError:'utf-16-le‘编解码器无法编码0位置的字符'\ud83d’:代孕者不允许>>>。
-
# -*- coding: utf-8 -*-
import sys, io
import os, codecs # for debugging
print(os.path.basename(sys.executable), sys.argv[0], '\n') # for debugging
#######################
### original answer ###
#######################
filepath = 'D:\\test\\reviews1.txt'
with io.open(filepath, mode='r',encoding='utf-8') as myfile:
document1=myfile.read() #.replace('\n', '')
document2=u''
for character in document1:
ordchar = ord(character)
if ordchar <= 0xFFFF:
# debugging # print( 'U+%.4X' % ordchar, character)
document2+=character
else:
# debugging # print( 'U+%.6X' % ordchar, '�')
### �=Replacement Character; codepoint=U+FFFD; utf8=0xEFBFBD
document2+='�'
print(document2) # original answer, runs universally
######################
### updated answer ###
######################
if os.path.basename(sys.executable) == 'pythonw.exe':
import struct
document3 = ''.join(c if c <= '\uffff' else ''.join(chr(x) for x in struct.unpack('>2H', c.encode('utf-16be'))) for c in document1)
print(document3) # Pythonw shell
else:
print(document1) # Python console输出,Pythonw:
==================重启: D:/test/Python/Py/q44965129a.py ================== pythonw.exe D:/test/Python/Py/q 44965129 a.�笑脸带微笑眼睛��笑脸��愤怒脸�笑脸带笑容张嘴笑脸>>>
输出,Python控制台:
==> D:\test\Python\Py\q44965129a.py
python.exe D:\test\Python\Py\q44965129a.py
� smiling face with smiling eyes �
� smiling face with open mouth �
� angry face �
smiling face with smiling eyes
smiling face with open mouth
angry face
==>发布于 2017-07-07 14:52:37
问题不在于读取文件(这将是de编码错误)。它与打印表达式有关:您的环境显然无法处理BMP以外的字符,例如表情符号。
如果要将这些字符打印到STDOUT,则可以检查shell/IDE是否支持支持所有Unicode (UTF-8、UTF-16.)的编码。或者切换到运行脚本的不同环境。
如果您想在相同的设置中运行它,您可以自己对数据进行编码,这使您可以选择指定自定义错误处理:
data = document1.encode('UCS-2', errors='replace')
sys.stdout.buffer.write(data)这将将不支持的字符替换为?或其他字符。您还可以指定errors='ignore',这将抑制字符。
不过,我无法测试这个,因为我的编解码库不知道UCS-2编码。这是Windows使用的一个过时的标准,直到NT。
https://stackoverflow.com/questions/44965129
复制相似问题