美文网首页
08-数据提取-正则表达式

08-数据提取-正则表达式

作者: Vanna_bot | 来源:发表于2019-03-06 18:37 被阅读0次
    • re模块的常见方法
    • 原始字符串r
    • 匹配中文

    re模块的常见方法

    • re.match()从头找一个
    • re.search()找一个
    • re.findal()找所有
      返回一个列表,没有就是空表
    ret = re.findall("\d","chuan1zhi2")
    >>['1', '2']
    
    • re.sub()替换
    re.sub("\d","_","wu1xuan2")
    >>wu_xuan_
    
    • re.compile()编译
      返回一个模型P,具有和re一样的方法,但是传递的参数不同
      匹配模式需要传到compile中
    p = re.compile("\d",re.S)
    p.findall("chuan1zhi2")
    

    python中原始字符串r的用法

    原始字符串(raw string):保持原先字符串中所有的字符
    如:“\n”的原始字符串就是“\\n”

    len("\n")
    >>1
    len(r"\n")
    >>2
    
    • 正则中使用原始字符串r忽略转义符号带来的影响

    匹配中文

    中文 unicode 编码范围:[u4e00-u9fa5](不包含中文标点)
    注意:汉字和正则表达式都需要是unicode字符操作
    【练习】提取中文

    # coding:utf-8
    import re
    
    title="<p>Look out your window and I`ll be gone</p> <p>看向你的窗外我早已离开</p> <p>You`re the reason I`m traveling on</p> <p>因为你我才四处漂泊</p> "
    
    p = re.findall(r"[\u4E00-\u9FA5]+",title)
    print(p)
    >>['看向你的窗外我早已离开', '因为你我才四处漂泊']
    

    相关文章

      网友评论

          本文标题:08-数据提取-正则表达式

          本文链接:https://www.haomeiwen.com/subject/hgodlqtx.html