Python (nltk) - UnicodeDecodeError: 'ascii' 编解码错误

9 投票
4 回答
6950 浏览
提问于 2025-04-18 18:29

我刚接触NLTK(自然语言工具包)。我遇到了这个错误,我查了一下关于编码和解码的内容,特别是UnicodeDecodeError,但这个错误似乎是和NLTK的源代码有关。

这是我遇到的错误:

Traceback (most recent call last):
  File "A:\Python\Projects\Test\main.py", line 2, in <module>
    print(pos_tag(word_tokenize("John's big idea isn't all that bad.")))
  File "A:\Python\Python\lib\site-packages\nltk\tag\__init__.py", line 100, in pos_tag
    tagger = load(_POS_TAGGER)
  File "A:\Python\Python\lib\site-packages\nltk\data.py", line 779, in load
    resource_val = pickle.load(opened_resource)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcb in position 0: ordinal not in range(128)

我该怎么解决这个错误呢?

这个错误的原因是:

from nltk import pos_tag, word_tokenize
print(pos_tag(word_tokenize("John's big idea isn't all that bad.")))

4 个回答

-2

试试使用“textclean”这个模块

>>> pip install textclean

Python代码

from textclean.textclean import textclean
text = textclean.clean("John's big idea isn't all that bad.")
print pos_tag(word_tokenize(text))
-2

重复内容:NLTK 3 的 POS_TAG 报错 UnicodeDecodeError

简单来说:NLTK 这个库不支持 Python 3。你需要使用 NLTK 3,但目前这个版本听起来有点不稳定。

4

我遇到过和你一样的问题。我在Windows 7上使用Python 3.4。

我安装了“nltk-3.0.0.win32.exe”(可以在这里找到)。但是当我安装“nltk-3.0a4.win32.exe”(可以在这里找到)时,我在使用nltk.pos_tag时的问题就解决了。你可以试试看。

补充:如果第二个链接打不开,你可以在这里查看。

5

试试这个... NLTK 3.0.1 和 Python 2.7.x 一起使用

import io
f = io.open(txtFile, 'rU', encoding='utf-8')

撰写回答