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

Lua string.gsub(s, pattern, func) 对应 Python 该怎么写啊?

  •  
  •   xpol · 2016-03-19 21:45:35 +08:00 · 3449 次点击
    这是一个创建于 2957 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Lua 的 string.gsub() 可以进行 regex 替换, 还可以跟一个回调函数,来处理如何将匹配的字符串转换成要替换的字符串:

        x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)
        --> x="home = /home/roberto, user = roberto"
    

    Python 有没有类似的方法啊。

    具体的说就是我要替换很多文件中的部分文本,匹配要匹配的文本方法就是固定的 regex ,而且同一个文件中可能有多处要替换。但是 regex 捕捉到文本后,要替换成什么文本是要用函数处理的。

    先谢谢大家了!

    第 1 条附言  ·  2016-03-21 08:49:57 +08:00
    这次是把我原来用 Lua 写的[脚本改成 Python]( https://github.com/xpol/cocos2d-x/blob/single-include-search-path/tools/coding-style/include-linter.py)。第一次觉得 Python 还是挺优雅的。
    4 条回复    2016-03-21 08:44:13 +08:00
    skydiver
        1
    skydiver  
       2016-03-19 21:55:02 +08:00   ❤️ 1
    http://lmgtfy.com/?q=python+regex+callback

    Google 一下前几条都是
    xpol
        2
    xpol  
    OP
       2016-03-19 22:00:32 +08:00
    谢谢,我也找到 re.sub 了。不习惯 python 不能定义多行的 lambda 。
    datou552211
        3
    datou552211  
       2016-03-20 22:37:37 +08:00 via iPhone
    @xpol 应该是没有大括号作用域的缘故啊
    xpol
        4
    xpol  
    OP
       2016-03-21 08:44:13 +08:00 via Android
    @datou552211 所以定义了一个辅助函数。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5352 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 07:30 · PVG 15:30 · LAX 00:30 · JFK 03:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.