zoukankan      html  css  js  c++  java
  • Python常用网页字符串处理技巧

    首先一些Python字符串处理的简易常用的用法。其他的以后用到再补充。

    1.去掉重复空格

    s = "hello   hello   hello"
    s = ' '.join(s.split())

    2.去掉所有回车(或其他字符或字符串)

    s = "hello
    hello
    hello hello
    "
    print(s)
    s = s.replace("
    ","")
    print(s)

    3.查找字符串首次出现的位置(没有返回-1)

    s = "hello
    hello
    hello hello
    "
    print(s.find('
    '))
    print(s.find('la'))

    4.查找字符串从后往前找首次出现的位置(没有返回-1)

    s = "hello
    hello
    hello hello
    "
    print(s.rfind('
    '))
    print(s.rfind('la'))

    5.将字符串转化成列表list

    s = "hello
    hello
    hello hello
    "
    print(list(s))

    6.查找所有匹配的子串

    import re
    
    s = "hello
    hello
    hello hello
    "
    print(re.findall('hello',s)) # hello也可以换成正则表达式

    然后是网页字符串处理的高端用法:(综合运用requests模块,beautifulsoup模块,re模块等)

    1.requests获取一个链接的内容并原封不动写入文件

    import requests
    
    r = requests.get('https://baike.baidu.com')
    with open('test.html', 'wb') as fd:
        for chunk in r.iter_content(100):
            fd.write(chunk)

    2.读取一个文件的所有内容存到一个字符串里

    # encoding : utf-8
    
    with open('test.html','r',encoding='utf-8') as f:
        content = f.readlines()
    content = ''.join(content)
    # content = content.replace('
    ','') # 如果想去掉回车可以加上这行
    print(content)

    3.把网页字符串用BeautifulSoup存起来处理

    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(content,'html.parser')
    print(soup.prettify())

    4.存到BeautifulSoup里之后这个字符串就可以任你摆布了,比如:提取出所有<a>标签

    soup = BeautifulSoup(content,'html.parser')
    print(soup.find_all('a'))

    或者提取出所有<a>标签和<b>标签

    soup = BeautifulSoup(content,'html.parser')
    print(soup.find_all(['a','b']))

    这些属于beautifulsoup的内容了,可以看官方文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/

    也可以看我的另一篇博客:http://www.cnblogs.com/itlqs/p/5902678.html

    5.多个关键字切分字符串

    import re
    re.split('; |, ',str)
    
    >>> a='Beautiful, is; better*than
    ugly'
    >>> import re
    >>> re.split('; |, |*|
    ',a)
    ['Beautiful', 'is', 'better', 'than', 'ugly']
  • 相关阅读:
    java bio 之聊天室
    自定义gradle plugin
    gradle build 找不到tools.jar 解决方法
    java switch case 枚举类型的反编译结果
    spring mvc 关键接口 HandlerMapping HandlerAdapter
    H5 Video 去除 下载按钮 禁用右键
    https 请求发送 例子 tls && ssl
    mac 安装mongodb
    (扫盲)DTO数据传输对象
    (扫盲)RPC远程过程调用
  • 原文地址:https://www.cnblogs.com/itlqs/p/5942374.html
Copyright © 2011-2022 走看看