如何在Python 3中使用slugify?

Kur*_*eek 16 python slugify

我正在尝试使用我安装的slugifypip3 install slugify.但是,在解释器中,如果我尝试敲击字符串,'hello'我会看到以下内容:

Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: from slugify import slugify

In [2]: slugify('hello')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-a58110f37579> in <module>()
----> 1 slugify('hello')

/usr/local/lib/python3.5/dist-packages/slugify.py in slugify(string)
     22 
     23     return re.sub(r'[-\s]+', '-',
---> 24             unicode(
     25                 re.sub(r'[^\w\s-]', '',
     26                     unicodedata.normalize('NFKD', string)

NameError: name 'unicode' is not defined

In [3]: slugify(u'hello')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-3-acc9f7b8d41e> in <module>()
----> 1 slugify(u'hello')

/usr/local/lib/python3.5/dist-packages/slugify.py in slugify(string)
     22 
     23     return re.sub(r'[-\s]+', '-',
---> 24             unicode(
     25                 re.sub(r'[^\w\s-]', '',
     26                     unicodedata.normalize('NFKD', string)

NameError: name 'unicode' is not defined
Run Code Online (Sandbox Code Playgroud)

相比之下,在Python 2中,后者确实有效:

Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
Type "copyright", "credits" or "license" for more information.

IPython 2.4.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: from slugify import slugify

In [2]: slugify(u'hello')
Out[2]: u'hello'
Run Code Online (Sandbox Code Playgroud)

如何在Python 3中使用它?

abc*_*ccd 33

你安装slugify包不是为python 3构建的,它目前只支持python 2.并且它不太可能会更新.最简单的方法之一就是在整个源代码中,它使用了python 2 unicode中不存在的python 2关键字.

你可能做到了:

pip install slugify
Run Code Online (Sandbox Code Playgroud)

这是一个过时的包,而不是你链接的包.

要安装你链接的slugify包,https: //pypi.python.org/pypi/python-slugify ,它python-slugify在你安装时调用,它支持所有最新的python版本.并有更多的功能.

pip install python-slugify
Run Code Online (Sandbox Code Playgroud)

并以与其他包相同的方式导入:

from slugify import slugify
Run Code Online (Sandbox Code Playgroud)

注意:您必须删除您安装的原始包,因为它们使用相同的名称.

  • 请注意 - 删除原始包:`pip uninstall slugify`。可能还需要重新启动环境(例如,我需要使用 Hydrogen 重新启动 Atom) (2认同)