推荐学习书目
› 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
ohmyzsh
V2EX  ›  Python

Python 如何使用正则提取中间文本

  •  
  •   ohmyzsh · Jan 1, 2018 · 3857 views
    This topic created in 3259 days ago, the information mentioned may be changed or developed.

    文本如下:

    A 公司生产的 aa 产品,B 公司生产的 bb 产品,C 公司生产的 cc 产品,...

    用 Python 该怎么把所有的产品名称( aa、bb、cc 等)提取出来保存为列表呢?谢谢!

    (product = re.findall(r"生产的(.*),", article) 为啥不对呢?)
    11 replies  •  2018-01-04 11:31:48 +08:00
    welkinzh
    welkinzh
    Jan 1, 2018
    1
    英文和中文之间有空格吧,还有逗号前面要加个反斜杠
    NotFounder
    NotFounder
    Jan 1, 2018❤️1
    2
    (.*?)这里加个问号(懒惰匹配)
    ohmyzsh
    ohmyzsh
    OP
    Jan 1, 2018
    3
    @radiocontroller 多谢。
    ohmyzsh
    ohmyzsh
    OP
    Jan 1, 2018
    4
    @welkinzh 哦,没有空格,按照 #2 的方法解决了
    Xiaobaixiao
    Xiaobaixiao
    Jan 2, 2018
    5
    (?<=生产的).+(?=产品)
    ohmyzsh
    ohmyzsh
    OP
    Jan 3, 2018
    6
    @Xiaobaixiao 试了下,您这个输出是空值
    Xiaobaixiao
    Xiaobaixiao
    Jan 3, 2018
    7
    @ohmyzsh 结合 #1 #2 的 那就是:(?<=生产的\s)(.*?)(?=\s 产品)
    ohmyzsh
    ohmyzsh
    OP
    Jan 3, 2018
    8
    @Xiaobaixiao 还是空值😅
    ohmyzsh
    ohmyzsh
    OP
    Jan 3, 2018
    9
    @Xiaobaixiao 生产的(.*?),

    #2 的这个可以
    Xiaobaixiao
    Xiaobaixiao
    Jan 3, 2018
    10
    @ohmyzsh 不会吧……
    >>> article='''A 公司生产的 aa 产品,B 公司生产的 bb 产品,C 公司生产的 cc 产
    品'''
    >>> re.findall('(?<=生产的\s)(.*?)(?=\s 产品)',article)
    ['aa', 'bb', 'cc']
    ohmyzsh
    ohmyzsh
    OP
    Jan 4, 2018
    11
    @Xiaobaixiao 把 re.findall('(?<=生产的\s)(.*?)(?=\s 产品)',article) 产品前的空格去掉可以了,多谢回复,新年好!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4110 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 09:07 · PVG 17:07 · LAX 01:07 · JFK 04:07
    ♥ Do have faith in what you're doing.