【发布时间】: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>
【问题讨论】: