代码之家  ›  专栏  ›  技术社区  ›  Peter Kim

Imdb review编码错误

  •  1
  • Peter Kim  · 技术社区  · 8 年前

    有一个词汇词典,在预处理中,我回顾了一些索引序列。
    例如

    “这部电影是最好的”->[2,5,10,3]

    num of reviews 100
    number of unique tokens : 4761
    Traceback (most recent call last):
      File "preprocess.py", line 47, in <module>
        print(vocab)
    UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 10561: ordinal not in range(128)
    

    代码如下:

    from bs4 import BeautifulSoup
    reviews = []
    for item in os.listdir('imdbdata/train/pos')[:100]:
        with open("imdbdata/train/pos/"+item,'r',encoding='utf-8') as f:
            sample = BeautifulSoup(f.read()).get_text()
        sample = word_tokenize(sample.lower())
        reviews.append(sample)
    print("num of reviews", len(reviews))
    word_freq = nltk.FreqDist(itertools.chain(*reviews))
    print("number of unique tokens : %d"%(len(word_freq.items())))
    vocab = word_freq.most_common(vocab_size-1)
    index_to_word = [x[0] for x in vocab]
    index_to_word.append(unknown_token)
    word_to_index = dict((w,i) for i,w in enumerate(index_to_word))
    print(vocab)
    

    问题是,我怎么能逃脱这个 UnicodeEncodeError 在用Python处理自然语言处理问题时?尤其是在使用 open 作用

    1 回复  |  直到 8 年前
        1
  •  1
  •   mhawke    8 年前

    看起来您的终端配置为ASCII。因为角色 '\xe9' 超出ASCII字符范围(0x00-0x7F),无法在ASCII终端上打印。它也不能编码为ASCII:

    >>> s = '\xe9'
    >>> s.encode('ascii')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 0: ordinal not in range(128)
    

    您可以在打印时显式编码字符串,并用替换不支持的字符来处理编码错误 ? :

    >>> print(s.encode('ascii', errors='replace'))
    b'?'
    

    您可以检查用于标准输出的编码。在我的例子中,它是UTF-8,我打印这个字符没有问题:

    >>> import sys
    >>> sys.stdout.encoding
    'UTF-8'
    >>> print('\xe9')
    é
    

    您可以强制Python使用不同的默认编码;有一些讨论 here ,但最好的方法是使用支持UTF-8的终端。