【问题标题】:UnicodeEncodeError: 'charmap' codec can't encode character '\x9f' in position 47: character maps to <undefined>UnicodeEncodeError:“charmap”编解码器无法在位置 47 编码字符“\x9f”:字符映射到 <undefined>
【发布时间】:2020-03-09 20:20:07
【问题描述】:

以下是将 bz2 转换为文本格式的代码。然而;我收到一个 unicode 错误。由于我使用的是 utf-8,我想知道错误可能是什么

from __future__ import print_function

import logging
import os.path
import six
import sys

from gensim.corpora import WikiCorpus

if __name__ == '__main__':
    program = os.path.basename(sys.argv[0])
    logger = logging.getLogger(program)

    logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s')
    logging.root.setLevel(level=logging.INFO)
    logger.info("running %s" % ' '.join(sys.argv))

    # check and process input arguments

    inp =  "trwiki-latest-pages-articles.xml.bz2"
    outp = "wiki_text_dump.txt"
    space = " "
    i = 0

    output = open(outp, 'w')
    wiki = WikiCorpus(inp, lemmatize=False, dictionary={})
    for text in wiki.get_texts():
        if six.PY3:
            output.write(' '.join(text).encode().decode('unicode_escape') + '\n')
        #   ###another method###
        #    output.write(
        #            space.join(map(lambda x:x.decode("utf-8"), text)) + '\n')
        else:
            output.write(space.join(text) + "\n")
            #output.write(text)
        i = i + 1
        if (i % 10000 == 0):
            logger.info("Saved " + str(i) + " articles")

    output.close()
    logger.info("Finished Saved " + str(i) + " articles")

错误:

UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-42-9404745af31b> in <module>()
     32     for text in wiki.get_texts():
     33         if six.PY3:
---> 34             output.write(' '.join(text).encode().decode('unicode_escape') + '\n')
     35         #   ###another method###
     36         #    output.write(

c:\users\m\appdata\local\programs\python\python37\lib\encodings\cp1254.py in encode(self, input, final)
     17 class IncrementalEncoder(codecs.IncrementalEncoder):
     18     def encode(self, input, final=False):
---> 19         return codecs.charmap_encode(input,self.errors,encoding_table)[0]
     20 
     21 class IncrementalDecoder(codecs.IncrementalDecoder):

UnicodeEncodeError: 'charmap' codec can't encode character '\x9f' in position 47: character maps to <undefined>

我也用“utf-8”替换了“unicode_escape”然后我得到了这个错误

UnicodeEncodeError: 'charmap' codec can't encode characters in position 87-92: character maps to <undefined>

【问题讨论】:

    标签: python xml unicode


    【解决方案1】:

    正如回溯所示,错误发生在调用.encode 期间,不是在调用.decode 期间。因此,您无法通过更改.decode 编解码器来解决此问题。

    由于代码在 Python 3.x 中运行(six.PY3 是正确的 - 但是您为什么关心今天编写的新代码中的 2.x 兼容性?),并且由于 ' '.join(text) 有效,我们得出结论 @987654328 @ 是字符串或字符串列表(不是bytesbytes 的列表),' '.join(text) 是字符串。事实上,documentation 告诉我们WikiCorpus 已经提供了字符串。

    此字符串包含一些您的编解码器 cp1254.py(这是专门用于土耳其语文本的 Windows 代码页)无法编码的字符。我不清楚您希望通过编码然后再次解码来完成什么。只需使用字符串。事实上,text 应该已经是一个不需要任何 .joining 的单个字符串(除非出于某种原因,您想在每个字母后放置一个空格)。您应该通过调试自己验证这一点。

    【讨论】:

    • text 是一个由多个字符串组成的列表。我试过 output.write(text) 但这也没有用。您能否详细说明我的代码的答案。我从textminingonline.com/… 复制了这段代码。我无法理解这一切:/
    • 当我使用 output.write(text) 时出现错误“TypeError: write() argument must be str, not list.”。
    • 我认为异常不是由.encode()调用引发的,而是由调用.write()TextIOWrapper对象的.write()方法时触发的隐式编码过程引发的。你来自open())。我同意.encode().decode() 毫无意义,应该删除,但它可能无法解决这里的问题。这里缺少的是open() 调用中的encoding="utf8" 参数。
    • 原因是:str.encode() 默认为 UTF-8,但open() 有一个依赖于平台的默认值(编解码器取决于语言环境和内容)。
    • when I use output.write(text) I get the error "TypeError: write() argument must be str, not list." 是的,正如它所说:您有一个 字符串列表,而不是单个字符串。您将单个字符串写入文件;因此,您必须分别迭代和写入列表中的每个字符串。
    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 2021-01-27
    • 2014-01-06
    • 1970-01-01
    • 2022-06-11
    • 2013-02-17
    • 1970-01-01
    • 2015-11-29
    相关资源
    最近更新 更多