Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x “UCS-2”无法编码_Python 3.x_Utf 8 - Fatal编程技术网

Python 3.x “UCS-2”无法编码

Python 3.x “UCS-2”无法编码,python-3.x,utf-8,Python 3.x,Utf 8,我试图读取文本文件,但它抛出一个错误 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.rea

我试图读取文本文件,但它抛出一个错误

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)

问题不在于读取可能是解码错误的文件。 这与打印表达式有关:您的环境显然无法处理字符以外的字符,例如表情符号

如果要将这些字符打印到标准输出,可以检查shell/IDE是否支持支持所有Unicode UTF-8、UTF-16…的编码。。。。 或者切换到其他环境以运行脚本

如果要在相同的设置下运行,可以自己对数据进行编码,这使您可以选择指定自定义错误处理:

data = document1.encode('UCS-2', errors='replace')
sys.stdout.buffer.write(data)
这会将不支持的字符替换为?或者其他的角色。 您还可以指定errors='ignore',这将抑制字符


不过,我无法测试这一点,因为我的编解码器库不知道UCS-2编码。在NT之前,它是Windows使用的过时标准。

我可以在Python版本3.5.1、Tk版本8.6.4、空闲版本3.5.1中重现该错误。这似乎是Tk中的一个bug。但是,在我的例子中,原始脚本可以从控制台Windows cmd平稳运行:Python 3.5.1 v3.5.1:37A07CEE59692015年12月6日01:54:25[MSC v.1900 64位AMD64]在win32上

我能看到的唯一方法可能非常慢:下面的注释脚本逐字符复制整个文档,将所有文档中的字符都删除

编辑:我找到了。不幸的是,这在Python shell中运行,但Python控制台抱怨:

-

输出,Pythonw shell:

===================重新启动:D:/test/Python/Py/q44965129a.Py================== pythonw.exe D:/test/Python/Py/q44965129a.Py � 笑容可掬� � 张嘴笑脸� � 愤怒的脸�
尝试尽管如此,请回答您的问题并显示完整的回溯。问题不在于读取文件会导致解码错误。这与打印表达式有关:您的环境显然无法处理字符以外的字符,例如表情符号。写入文件是一个选项吗?我可以在Python3.5空闲环境中重现这个错误。但是,在我的例子中,脚本在控制台Windows cmd上运行平稳@lenz是对的,错误与打印有关。是的,但如何克服它@JosefZI首先将数据保存到同一个文件中。现在我正在尝试读取和打印该文件的数据。是否存在这样的情况,我们可以在书写或阅读时删除该字符@谢谢你的帮助。既然内置的open也这么做,为什么还要使用io.open呢?当str.encode提供errors='replace'模式时,为什么要用手动检查迭代字符方式呢?不要重新发明轮子…@lenz1。我知道。这是OP的设计……2。您是否尝试应用任何错误处理程序?显然,你没有:不过你不能测试这个!哦,我没看到你把io.open从OP中拿走——很抱歉为此责备你。关于测试:是的,很遗憾。根据OP的错误消息,必须有一个具有UCS-2编解码器的Python版本/实现;也许它只在Windows上可用。你能执行我的建议吗?
>>> 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