Search code examples
pythonmoduleargparsedetection

error: no module named 'langdetect' when using argparse


I'm writing a program where a user inputs the name of a text file and the text can be altered in multiple ways. In order to do that, I need to detect the language of the text and I've chosen langdetect for now because of its compatibility with spacy. On its own langdetect works just fine, but I need to use argparse to get user input and that's when the error arises.

I have installed langdetect via pip and did the following imports:

from langdetect import detect
import langdetect

When I try to use langdetect it runs perfectly fine this way:

lang1 = langdetect.detect("Hallo meine Freunde")
print(lang1)

lang2 = detect("What's up my guys")
print(lang2)

results

de
en

However, when I use argparse to run the code on a conditional argument, python throws the error 'No module named 'langdetect''

import argparse
from langdetect import detect
import langdetect

parser = argparse.ArgumentParser()

parser.add_argument("-f", "--foo")
args = parser.parse_args()

if args.foo:
    lang1 = langdetect.detect("Hallo meine Freunde")
    print(lang1)

    lang2 = detect("What's up my guys")
    print(lang2)

Run code via

python3 main.py -f

The expected outcome should be the same as in the example above.

I'm not sure why it works when run via PyCharm but not when implemented in argparse and called via the cmd. Otherwise argparse works fine as well, it's just the combination of argparse and langdetect giving me trouble.


Solution

  • I executed your code on colab and it showed no errors.

    code snippet

    As I was going through the comments, you mentioned having Python and Python3. I guess it must be the case that you have langdetect installed in Python and not Python3. You should check the installed libraries using pip list or pip3 list. That should clear things up.

    Hope this works!