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

一堆re求化简

  •  
  •   ThunderEX · 2012-12-24 00:03:20 +08:00 · 3133 次点击
    这是一个创建于 4135 天前的主题,其中的信息可能已经有所发展或是发生改变。
    我有一串长长的:
    for line in open('.txt'):

    m = re.match(exp1, line, re.IGNORECASE)
    if m:
    func1(m.group())
    continue

    m = re.match(exp2, line, re.IGNORECASE)
    if m:
    func2(m.group())
    continue

    m = re.match(exp3, line, re.IGNORECASE)
    if m:
    func3(m.group())
    continue

    ......
    一来有一堆的正则解析和处理,二来别的别的地方还会调用其中几条,因而求教该怎么化简?
    最初的想法是弄一个字典包含像exp1:func1, exp2:func2,然后一个for逐条解析,但是字典是无序的,因而不能按照上面的顺序一条一条跑。
    然后觉得可以新建一个类,每个解析方法各弄一条子类,但是好像要写很多的样子……
    总之想看看大神们怎么写的……
    4 条回复    1970-01-01 08:00:00 +08:00
    reusFork
        1
    reusFork  
       2012-12-24 00:11:36 +08:00   ❤️ 1
    rules = [(exp1, func1), (exp2, func2), (exp3, func3)]
    for l in lines: for exp, func in rules: if …………
    wwwjfy
        2
    wwwjfy  
       2012-12-24 00:21:12 +08:00
    python有个东西叫OrderredDict
    wwwjfy
        3
    wwwjfy  
       2012-12-24 00:21:43 +08:00
    写错了,OrderedDict
    ThunderEX
        4
    ThunderEX  
    OP
       2012-12-24 00:32:22 +08:00 via Android
    @reusFork 唔…是我把问题想复杂了…好像新手都会把问题想复杂?为什么…
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1020 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 19:10 · PVG 03:10 · LAX 12:10 · JFK 15:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.