使用 NLTK 的 Python 在 sent_tokenize 和 word_tokenize 处显示错误

标签 python nltk

我正在使用 Google Colab 编写通过视频学习的脚本。不幸的是,我按照视频说明操作时遇到错误。

sentences_tokens=nltk.sent_tokenize(allParagraphContent_cleanedData)
words_tokens=nltk.word_tokenize(allParagraphContent_cleanedData)

引起问题。两条线。我已经在 Python 3(我主要使用它)中单独尝试了其中的每一个。 以下是导入的库:

from urllib import request
from bs4 import BeautifulSoup as bs
import re
import nltk
import heapq

我得到的错误是:

---------------------------------------------------------------------------

LookupError                               Traceback (most recent call last)

<ipython-input-13-2467ae276de5> in <module>()
     26 allParagraphContent_cleanedData=re.sub(r'\s+','',allParagraphContent_cleanedData)
     27 
---> 28 sentences_tokens=nltk.sent_tokenize(allParagraphContent_cleanedData)
     29 words_tokens=nltk.word_tokenize(allParagraphContent_cleanedData)
     30 

坦白说,我不明白这个错误。

我没有看到什么问题?

-- 这是完整的代码

from urllib import request
from bs4 import BeautifulSoup as bs
import re
import nltk
import heapq



url="https://en.wikipedia.org/wiki/Machine_learning"
allParagraphContent = ""
htmlDoc=request.urlopen(url)
soupObject=bs(htmlDoc,'html.parser')



for paragraphContent in paragraphContents:
    allParagraphContent += paragraphContent.text


allParagraphContent_cleanerData=re.sub(r'\[0-9]*\]','',allParagraphContent)
allParagraphContent_cleanedData=re.sub(r'\s+','',allParagraphContent_cleanerData)



allParagraphContent_cleanedData=re.sub(r'[^a-zA-Z]','',allParagraphContent_cleanedData)
allParagraphContent_cleanedData=re.sub(r'\s+','',allParagraphContent_cleanedData)

sentences_tokens=nltk.sent_tokenize(allParagraphContent_cleanedData)
words_tokens=nltk.word_tokenize(allParagraphContent_cleanedData)

解决办法: 在 import nltk

之后添加 nltk.download("popular")

最佳答案

当模块丢失时,通常会出现此错误。这可以通过使用 download() 方法并指定模块来解决。此外,您可以传递 'all' 并下载所有内容。代码是:

nltk.download('all')

关于使用 NLTK 的 Python 在 sent_tokenize 和 word_tokenize 处显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60116885/

相关文章:

python - 训练 Keras 序列模型时损失没有减少

python - 启动 Python shell 时出错,一周前运行的脚本出错

python - PyPy 可以与 NLTK 一起使用吗?

python - 仅从 (word,pos_tag) 元组获取 POS 标签列表

python - 如何创建未链接到原始对象的 python 对象的副本?

python - 以漂亮的格式打印字典键的简洁方法

python - 在 Oozie 中运行 python 脚本时如何导入本地 python 模块?

python - Python 的 collections.Counter 和 nltk.probability.FreqDist 之间的区别

python - 过滤特定语音部分 NLTK

nlp - NLTK 的 WordNet 中的 part_meronyms 和 member_meronyms 有什么区别?