整理的一些在使用Python中常用网页字符串处理方法

首先一些Python字符串处理的简易常用的用法。

1.去掉重复空格

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

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

s = "hello\nhello\nhello hello\n"
print(s)
s = s.replace("\n","")
print(s)

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

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
s = "hello\nhello\nhello hello\n"
print(s.find('\n'))
print(s.find('la'))

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

s = "hello\nhello\nhello hello\n"
print(s.rfind('\n'))
print(s.rfind('la'))

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

s = "hello\nhello\nhello hello\n"
print(list(s))

6.查找所有匹配的子串

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import re

s = "hello\nhello\nhello hello\n"
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.读取一个文件的所有内容存到一个字符串里

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
with open('test.html','r',encoding='utf-8') as f:
    content = f.readlines()
content = ''.join(content)
# content = content.replace('\n','') # 如果想去掉回车可以加上这行
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>标签

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
soup = BeautifulSoup(content,'html.parser')
print(soup.find_all(['a','b']))

这些属于beautifulsoup的内容了

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

import re
re.split('; |, ',str)

>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值