我可以在Python IDLE environment (Python version 3.5.1, Tk version 8.6.4, IDLE version 3.5.1) 中重现错误。这似乎是Tk 中的一个错误。但是,原始脚本可以从控制台顺利运行(在我的情况下是 Windows cmd):Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:54:25) [MSC v.1900 64 bit (AMD64)] on win32。
我能看到的唯一方法可能是非常慢:以下注释脚本逐个字符地复制整个文档,消除了Basic Multilingual Plane中的所有字符。
编辑:我找到了this (more Python-ish) solution (thanks to Mark Ransom)。不幸的是,这在 Python shell 中运行,但 Python 控制台抱怨:
>>> print( ''.join(c if c <= '\uffff' else ''.join(chr(x) for x in struct.unpack(
... '>2H', c.encode('utf-16be'))) for c in document1)
... )
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "C:\Python\Python35\lib\site-packages\win_unicode_console\streams.py",
line 179, in write
return self.base.write(s)
UnicodeEncodeError: 'utf-16-le' codec can't encode character '\ud83d' in position 0:
surrogates not allowed
>>>
-
# -*- 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 shell:
================== RESTART: D:/test/Python/Py/q44965129a.py ==================
pythonw.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 ?
>>>
输出,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 ?
==>