【问题标题】:UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128) [duplicate]UnicodeDecodeError:“ascii”编解码器无法解码位置 5 中的字节 0xc3:序数不在范围内(128)[重复]
【发布时间】:2019-05-10 23:37:04
【问题描述】:

我目前正在编写一个程序,该程序利用 Python NLTK 库来确定评论是正面还是负面。尝试标记每个单词并将其存储在数组中时,我不断收到上述错误。错误行之前和之前的代码行是:

from nltk.tokenize import word_tokenize

...

short_pos = open("reviews/pos_reviews.txt", "r").read()
short_neg = open("reviews/neg_reviews.txt", "r").read()

documents = []

for r in short_pos.split('\n'):
    documents.append( (r, "pos") )

for r in short_neg.split('\n'):
    documents.append( (r, "neg") )

all_words = []

short_pos_words = word_tokenize(short_pos)
short_neg_words = word_tokenize(short_neg)

倒数第二行是说我有错误的地方。如果我注释掉该行,错误将出现在下一行。我不确定这个错误会出现在哪里,因为我认为我根本没有使用 unicode。任何帮助将不胜感激!

【问题讨论】:

  • 你用的是什么版本的python?
  • @candied_orange 我的代码在 v2.7.15 上运行

标签: python nltk tokenize


【解决方案1】:

在Python 2.7中,尝试使用io模块指定文件编码,见Difference between io.open vs open in python

另外,上下文管理器是你的朋友(即with ... as ...),尤其是。说到 I/O https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/

import io

from nltk.tokenize import word_tokenize

documents = []

with io.open("reviews/pos_reviews.txt", "r", encoding="utf8") as fin:
    for line in fin:
        documents.append((line.strip(), "pos"))

【讨论】:

    猜你喜欢
    • 2014-08-19
    • 2015-05-05
    • 2016-11-12
    • 2016-06-30
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多