开发者社区> 问答> 正文

python模块导入问题,大神求解释?报错

 

刚开始代码

from xml.parsers.expat import ParserCreate

class DefaultSaxHandler(object):
    def start_element(self, name, attrs):
        print('sax:start_element: %s, attrs: %s' % (name, str(attrs)))

    def end_element(self, name):
        print('sax:end_element: %s' % name)

    def char_data(self, text):
        print('sax:char_data: %s' % text)

xml = r'''<?xml version="1.0" encoding="UTF-8"?>
<ol>
    <li><a
    <li><a
</ol>
'''
handler = DefaultSaxHandler()
parser = ParserCreate()
parser.returns_unicode = True
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data
parser.Parse(xml)

然后报错

    from xml.parsers.expat import ParserCreate
ImportError: No module named parsers.expat

打印sys.path


['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-i386-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client']




然后上面改为



#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sys
sys.path.append("/usr/lib/python2.7/xml/parsers/")

from expat import ParserCreate


class DefaultSaxHandler(object):
    def start_element(self, name, attrs):
        print('sax:start_element: %s, attrs: %s' % (name, str(attrs)))

    def end_element(self, name):
        print('sax:end_element: %s' % name)

    def char_data(self, text):
        print('sax:char_data: %s' % text)

xml = r'''<?xml version="1.0" encoding="UTF-8"?>
<ol>
    <li><a
    <li><a
</ol>
'''
handler = DefaultSaxHandler()
parser = ParserCreate()
parser.returns_unicode = True
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data
parser.Parse(xml)


就好了.小白问一句,刚开始的那段代码

from xml.parsers.expat import ParserCreate

为什么找不到对应的模块呢



展开
收起
爱吃鱼的程序员 2020-06-12 14:27:33 595 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    你调用的模块的路径不在系统环境中(PATH)你的xml模块怎么安装的?用pip吗?

    我想问,你试过 

    fromxmlimport<spanstyle="font-size:13.3333330154419px;">parsers.expat.ParserCreate

    这种方法吗?你仔细查看一下这些目录,是否缺少了__init__.py文件。如果缺少了,那么python不会认为这个目录是模块的。

    2020-06-12 14:27:49
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载