0

我在 Mac 上安装了 lxml 并尝试在我的代码中使用它,但在导入 tostring 和 tounicode 时出现错误。Python 根本看不到它。任何想法我做错了什么?

这是导致问题的代码 -

from lxml.etree import tostring
from lxml.etree import tounicode

我收到未解决的导入错误

我的 IDE (eclipse) 也能够看到 lxml.etree 模块的init .py 文件。这是它所看到的——

# this is a package

def get_include():
    """
    Returns a list of header include paths (for lxml itself, libxml2
    and libxslt) needed to compile C code against lxml if it was built
    with statically linked libraries.
    """
    import os
    lxml_path = __path__[0]
    include_path = os.path.join(lxml_path, 'includes')
    includes = [include_path, lxml_path]

    for name in os.listdir(include_path):
        path = os.path.join(include_path, name)
        if os.path.isdir(path):
            includes.append(path)

    return includes

谢谢你的帮助。

编辑:
我看到的唯一日志是 Unresolved import: tostring Unresolved import: tounicode

当我在导入 tostring 之前添加以下行时,它不会出现错误 - 从 lxml 导入 etree

也给你一些关于我正在尝试做的事情的背景。我从这里(https://github.com/buriy/python-readability)获得了可读性代码,并尝试在我的项目中使用它。

EDIT2:我解决了这个问题,但仍然不明白为什么。我想直接使用可读性项目中的代码,而不使用 easy_install 安装包。这个想法是进入代码,以便我了解它在做什么。但是当我将代码复制到我的项目中时,我在可读性代码中得到了上述错误。如果我使用 easy_install 安装包,那么我可以简单地导入通过可读性导出的类并使用它。

那么有人能告诉我直接使用代码和安装包之间有什么区别吗?什么是 .egg 文件?如何创建一个?

4

2 回答 2

1

在 lxml 的代码中,它动态加载模块。这使得 IDE 无法分析引用,因为 IDE 仅分析原始代码。

于 2017-09-08T04:00:25.247 回答
0

etree在我的 Intellij IDEA Python 项目中尝试解析资源和导入时,我发现此解决方案非常有用:

看看建议这个解决方案的lxml 教程:

try:
    from lxml import etree
    print("running with lxml.etree")
except ImportError:
    try:
        # Python 2.5
        import xml.etree.cElementTree as etree
        print("running with cElementTree on Python 2.5+")
    except ImportError:
        try:
            # Python 2.5
            import xml.etree.ElementTree as etree
            print("running with ElementTree on Python 2.5+")
        except ImportError:
            try:
                # normal cElementTree install
                import cElementTree as etree
                print("running with cElementTree")
            except ImportError:
                try:
                    # normal ElementTree install
                    import elementtree.ElementTree as etree
                    print("running with ElementTree")
                except ImportError:
                    print("Failed to import ElementTree from any known place")
于 2017-12-11T13:41:17.010 回答