17

I've downloaded the python-Levenshtein archive and extracted Levenshtein dir. So, in result I have the following files structure:

Levenshtein
  - __init__.py
  - _levenshtein.c
  - _levenshtein.h
  - StringMatcher.py
myscript.py

And the following myscript.py content:

from Levenshtein import *
from warnings import warn

print Levenshtein.distance(string1, string2)

But I get the following error -

Traceback (most recent call last):
  File "myscript.py", line 1, in <module>
    from Levenshtein import *
  File "/path/to/myscript/Levenshtein/__init__.py", line 1, in <module>
    from Levenshtein import _levenshtein
ImportError: cannot import name _levenshtein

What is wrong here?

LA_
  • 19,823
  • 58
  • 172
  • 308

4 Answers4

25

To install the python-Levenshtein package:

  • pip install python-levenshtein

(This requires pip, but most modern Python installations include it.)

abarnert
  • 354,177
  • 51
  • 601
  • 671
Franck Dernoncourt
  • 77,520
  • 72
  • 342
  • 501
16

It seems to me like you did not build the Levenshtein package. Go to the unextracted directory of the source you downloaded (for example, python-Levenshtein-0.12.0/) and build with:

python setup.py build

If all went well (apart, possibly, from some warnings), install to your site-packages with

sudo python setup.py install

Then I find I can use the package. e.g. from within IPython:

In [1]: import Levenshtein
In [2]: string1 = 'dsfjksdjs'
In [3]: string2 = 'dsfiksjsd'
In [4]: print Levenshtein.distance(string1, string2)
3

(Note that with your (perhaps unwise) wildcard import you should just be using distance(string1, string2) without prefixing with the package name).

xnx
  • 24,509
  • 11
  • 70
  • 109
13

Installation and usage of Levenshtein PIP package on Windows, Mac and UNIX

Install with sudo or run as admin

pip install python-levenshtein

Import in your code with:

import Levenshtein as lev

than in your code you can use Levenstein functions like this

lev.distance('Levenshtein', 'Lenvinsten')

which will output

4

.

Hrvoje
  • 13,566
  • 7
  • 90
  • 104
-1

You may try to set environment variables:

append the paths of catalogs python-Levenshtein-master\build\lib.win-amd64-2.7\Levenshtein and python-Levenshtein-master\build\temp.win-amd64-2.7\Release\Levenshtein to your system environment variable PATH.

Silas Parker
  • 8,017
  • 1
  • 28
  • 43
Alex Wang
  • 59
  • 1
  • 5