NameError: 名称 ‘nltk’ 未在 Python 中定义
NameError: name ‘nltk’ is not defined in Python
Python“NameError: name ‘nltk’ is not defined”发生在我们使用
nltk
模块而不先导入它时。要解决该错误,请安装模块并import nltk
在使用前将其导入 ( )。
在项目的根目录中打开终端并安装nltk
模块。
壳
# 👇️ in a virtual environment or using Python 2 pip install nltk # 👇️ for python 3 (could also be pip3.10 depending on your version) pip3 install nltk # 👇️ if you get permissions error sudo pip3 install nltk # 👇️ if you don't have pip in your PATH environment variable python -m pip install nltk # 👇️ for python 3 (could also be pip3.10 depending on your version) python3 -m pip install nltk # 👇️ for Anaconda conda install -c anaconda nltk
安装nltk模块后,确保在使用前导入它。
主程序
# ✅ import nltk first import nltk # 👇️ download nltk libraries if necessary nltk.download() sentence = """At eight o'clock on Thursday morning Arthur didn't feel very good.""" tokens = nltk.word_tokenize(sentence) print(tokens)
nltk.download()
如果您不必下载任何与 nltk 相关的库,则可以删除该行。
确保您没有拼错要导入的模块,因为模块名称区分大小写。
此外,请确保您没有从nltk
嵌套范围(例如函数)中导入。在顶层导入模块,以便能够在整个代码中使用它。
结论
Python“NameError: name ‘nltk’ is not defined”发生在我们使用
nltk
模块而不先导入它时。要解决该错误,请安装模块并import nltk
在使用前将其导入 ( )。