V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
vtoexsir
V2EX  ›  Python

python 怎么给原有模块添加自定义方法?

  •  
  •   vtoexsir · 2016-10-10 13:34:12 +08:00 · 2083 次点击
    这是一个创建于 2761 天前的主题,其中的信息可能已经有所发展或是发生改变。

    from bs4 import BeautifulSoup as bs soup=bs(html_code) #伪代码 text=soup.get_text() #这个 get_text()方法是 bs 定义好了的方法 my_text=soup.my_get_text() #这个 my_get_text()方法是 bs 没有的方法,会报异常

    如上代码,比如 bs 中本来没有 my_get_text()这个方法,我是否可以写一个自定义模块,比如叫做'my_bs',

    import my_bs

    当如上导入自定义的模块后, 就能正常运行如下代码:my_text=soup.my_get_text() 说白了,我就是想给已有的 bs4 包添加一个我自己定义的方法. 但是不是通过修改 bs4 的源代码,而是自定义一个模块, 在自己的代码中导入自定义模块来达到目的. 多谢!

    6 条回复    2016-10-10 19:36:26 +08:00
    masterzh01
        1
    masterzh01  
       2016-10-10 13:38:35 +08:00
    masterzh01
        2
    masterzh01  
       2016-10-10 13:39:19 +08:00
    clino
        3
    clino  
       2016-10-10 13:41:04 +08:00
    如果是类就继承派生一个新类来用是不是就行了
    yangtukun1412
        4
    yangtukun1412  
       2016-10-10 13:41:36 +08:00
    monkey patch.
    ty89
        5
    ty89  
       2016-10-10 13:56:25 +08:00
    import some_module

    class PatchedClass(object):
    ...

    some_module.TheClass = PatchedClass
    vtoexsir
        6
    vtoexsir  
    OP
       2016-10-10 19:36:26 +08:00
    新建 myBS.py 文件,内容如下:
    import bs4


    def getTextWithoutScript(self, separator=u"", strip=False,
    withoutScript=True, withoutComment=True):
    """获取网页文本,不包含 html 源码中的 script 脚本的内容"""
    return separator.join([s for s in self._all_strings(strip) if s.parent.name.lower() != 'script'])


    bs4.Tag.getTextWithoutScript = getTextWithoutScript

    使用方法:
    首先导入 myBS.py,其他使用方法就是直接调用,与 bs 的原生方法一样:
    import myBS
    from bs4 import BeautifulSoup as bs

    s=bs(html_code,'html5lib')
    s.getTextWithoutScript()

    不方便的地方:在 pycharm 下该新加入 BS 的方法不能智能提示!
    感谢诸位老师!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2103 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:29 · PVG 19:29 · LAX 04:29 · JFK 07:29
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.