Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import and use python Levenshtein extension on OSX?

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?

like image 421
LA_ Avatar asked Jan 27 '15 13:01

LA_


3 Answers

To install the python-Levenshtein package:

  • pip install python-levenshtein

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

like image 85
Franck Dernoncourt Avatar answered Sep 19 '22 02:09

Franck Dernoncourt


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).

like image 30
xnx Avatar answered Sep 20 '22 02:09

xnx


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

.

like image 39
Hrvoje Avatar answered Sep 22 '22 02:09

Hrvoje