【问题标题】:IOError when loading NLTK perceptron tagger加载 NLTK 感知器标记器时出现 IOError
【发布时间】:2016-08-21 10:15:11
【问题描述】:

代码简单如下

import nltk
nltk.data.path.append(r"E:\nltk_data")
nltk.pos_tag(["hello"])

错误是

File "C:\Program Files (x86)\IronPython
2.7\lib\site-packages\nltk\tag\__init__.py", line 110, in pos_tag
    tagger = PerceptronTagger()   File "C:\Program Files (x86)\IronPython 2.7\lib\site-packages\nltk\tag\perceptron.py", line 141, in __init__
    self.load(AP_MODEL_LOC)   File "C:\Program Files (x86)\IronPython 2.7\lib\site-packages\nltk\tag\perceptron.py", line 209, in load
    self.model.weights, self.tagdict, self.classes = load(loc)   File "C:\Program Files (x86)\IronPython
2.7\lib\site-packages\nltk\data.py", line 800, in load
    # Load the resource.   File "C:\Program Files (x86)\IronPython 2.7\lib\site-packages\nltk\data.py", line 921, in _open
    # urllib might not use mode='rb', so handle this one ourselves:   File "C:\Program Files (x86)\IronPython
2.7\lib\site-packages\nltk\data.py", line 603, in find
    if zipfile is None:   File "C:\Program Files (x86)\IronPython 2.7\Lib\nturl2path.py", line 26, in url2pathname
    raise IOError, error IOError: Bad URL: /C|/E|/nltk_data/taggers/averaged_perceptron_tagger/averaged_perceptron_tagger.pickle

url怎么会变成/C|/E|/nltk_data/tagg...,为什么要调用url2pathname呢?我已经在 Windows 上,我提供的 url 是 Windows 样式的 url。

【问题讨论】:

    标签: python nltk ironpython


    【解决方案1】:

    我不得不深入研究代码,最终发现了问题。 Nltk用if sys.platform.startswith('win'):判断操作系统(非常专业的判断方式,顺便)

    但是,如果您使用 IronPython,您的平台是 CLI

    我怀疑这会给 IronPython 用户带来很多问题。因此,下次任何 Python 包的行为都像它的 unix 对应物一样,只需检查此代码的模块即可。

    编辑:我的解决方法是用sys.platform.startswith('win') or sys.platform.startswith('cli')替换检查代码。

    【讨论】:

    • 我不确定NLTK 是否支持 IronPython,我知道即使使用 PyPy 它也会中断。在安装页面,已知NLTK在Windows(32位)和Mac/Unix上支持Python(尤其是CPython),NLTK requires Python versions 2.7 or 3.2+nltk.org/install.html=)
    • 请注意,尽管 IronPython 在名称中包含 Python,但实际上并不是通常所说的 Python(即CPython)。
    • @alvas 到目前为止,我们已将 Python 应用程序完全迁移到 IronPython 并且所有内容都经过了测试。我的结论是 NLTK 与 IronPython 完全兼容。 (当然还有其他模块我们没有使用或测试过。但该应用程序几乎使用了 NLTK 中的大部分模块)
    • 如果在主 repo 上的 IronPython 上有一个回归测试会很好,如果你愿意的话,如果你已经重写了测试,请随时提出并发出请求请求IronPython 用于 NLTK。提前致谢! =)
    • 人们希望文本分析库的作者会找到比startswith() 更好的检查平台字符串的方法:)
    【解决方案2】:

    您的代码正在转义 \n:

    \ 替换为\\

    import nltk
    nltk.data.path.append(r"E:\\nltk_data")
    nltk.pos_tag(["hello"])
    

    你可以参考这个问题:What exactly do "u" and "r" string flags do in Python, and what are raw string literals?

    有关原始字符串文字如何工作的更多信息。

    【讨论】:

    • 我试过 [r"E:\\nltk_data"], ["E:\\nltk_data"], [r"E:\nltk_data"], [ur"E:\nltk_data" ]、[u"E:\\nltk_data"] 和 [u"E:\nltk_data"] 。他们都给了我同样的错误。这就是为什么我认为这与路径无关。
    猜你喜欢
    • 2016-11-29
    • 2017-01-30
    • 2011-04-25
    • 2021-11-02
    • 2010-12-12
    • 2011-06-07
    • 2017-10-11
    • 2013-03-13
    • 2013-01-08
    相关资源
    最近更新 更多