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
omg21
V2EX  ›  Python

怎样只把标签代码改为小写?

  •  
  •   omg21 · 2016-11-30 13:41:56 +08:00 · 1675 次点击
    这是一个创建于 2676 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我想把<>标签代码改成小写,其余部分不变应该怎么写?
    比如把<DIV>Windows XP</DIV>改成<div>Windows XP</div>

    想用正则替换,但是没想好应该怎么做。
    pattern = re.compile(r'<!--(.*?)/-->',re.I|re.S)
    htmlstr = re.sub(pattern,'',htmlstr)
    3 条回复    2016-11-30 14:27:12 +08:00
    halfcrazy
        1
    halfcrazy  
       2016-11-30 14:11:06 +08:00
    ```python
    # -*- coding: utf-8 -*-
    import re

    pattern = "</?(\w+)>"
    txt = "<DIV>Windows XP</DIV><A>Windows XP</A><script>Windows XP</script>"


    def _sub(matchobj):
    return matchobj.group(0).replace(matchobj.group(1),
    matchobj.group(1).lower())

    print(re.sub(pattern, _sub, txt))

    ```
    halfcrazy
        2
    halfcrazy  
       2016-11-30 14:22:56 +08:00
    @halfcrazy 考虑到存在单标签的情况。正则式需要修改一下`pattern = "</?(\w+)(?:[\s\S])*?/?>"`
    omg21
        3
    omg21  
    OP
       2016-11-30 14:27:12 +08:00
    @halfcrazy 谢谢,这要让我自己想,想三天也想不出来个结果
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5314 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 54ms · UTC 08:07 · PVG 16:07 · LAX 01:07 · JFK 04:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.