使用 fastText 执行示例代码时遇到问题

Trouble to execute sample code using fastText

背景

我想执行代码以使用 fastText 对每个文本的语言进行分类。

我做了什么

$ git clone https://github.com/facebookresearch/fastText.git
$ cd fastText
$ pip install .

上面的模型 lid.176.bin 和文件夹 fastText 与下面 python 代码存在同一级别。

我不知道如何避免这个错误。

错误

ImportError: No module named fastText

代码

sample.py

from fastText import load_model
model = load_model("lid.176.bin")

speech_texts = ["Hello, guys. What's up?", '你好! 我是学生。', 'Hallo, ich habe das Buch.']

def categorize(texts):
    for i in range(len(texts)):
        text = texts[i]
        label, prob = model.predict(text, k)
        return list(zip([l.replace("__label__", "") for l in label], prob))

categorize(speech_texts)

对答案的回应

  1. 我已经尝试按照答案执行命令,但我仍然在努力修复同样的错误。
$ pip3 install fasttext
Requirement already satisfied: fasttext in /usr/local/lib/python3.9/site-packages (0.9.2)
Requirement already satisfied: setuptools>=0.7.0 in /usr/local/lib/python3.9/site-packages (from fasttext) (51.1.1)
Requirement already satisfied: numpy in /usr/local/lib/python3.9/site-packages (from fasttext) (1.19.5)
Requirement already satisfied: pybind11>=2.2 in /usr/local/lib/python3.9/site-packages (from fasttext) (2.6.1)
    from fasttext import load_model
ImportError: No module named fasttext
  1. 我安装的包
$ pip3 freeze
fasttext @ file:///Users/username/Desktop/sample/fastText
numpy==1.19.5
pybind11==2.6.1

开发环境

Python 3.9

Mac OS 大苏尔

你应该使用:

from fasttext import load_model

解释为 in the documentation

作为最佳实践,您应该使用Python“虚拟环境”。

虽然避免这种混淆并不是绝对必要的,但通过采用保持 工作 python 和相关库 的纪律 特定项目 系统 python 分开,在您的脑海中和您的文件系统中,很多东西将明确分开且更清晰。

使用虚拟环境的两种合理方式是 之一:

一旦您养成了使用显式环境的习惯,在您验证了两件事后,像您这样的问题往往就会消失:

  1. 在执行 pip install PKG 之前,您是否正确激活了正确的环境? (在许多使用 conda 的情况下,您可能更喜欢 conda install PKG 以获得他们的额外优化包——尽管标准 pip 也适用于那里。)

  2. 您是否在安装必要库的正确(相同)环境中执行代码?

如果您正在使用环境并验证这两件事,您通常不会对当前执行的代码是否可以使用您已安装的库感到困惑。

由于在 MacOS 上 Python 2 和 Python 3 共存 – 在本质上不同的虚拟环境中,因此您当前的问题也可能变得更加棘手。您使用简单的 pythonpip 调用所做的任何事情都使用默认的 Python 2。默认情况下,要安装或执行 Python 3,您需要使用pip3python3。使用 pip3 安装的某些内容对于普通的 python 执行可能不可见,从而产生类似于您遇到的错误。 (一旦你开始使用 conda 的真实 venv,它可能会变成一个普通的 pythonpip 调用, 在激活的虚拟环境,选择适合该环境的 Python 3 可执行文件。)