使用正则表达式,取得点击次数,函数抽离

本文介绍了如何利用正则表达式实现多种实用功能,包括验证电子邮件格式、提取电话号码、英文分词、获取新闻编号及点击次数等。通过具体代码示例展示了正则表达式的强大之处。

1. 用正则表达式判定邮箱是否输入正确。

import re
def validateEmail(email):
    if len(email) > 7:
        if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:
            print('good')
            # return 1
    # return 0
    print('exit')
validateEmail('282649417@qq.com')

2. 用正则表达式识别出全部电话号码。

tel='版权所有:广州商学院   地址:广州市黄埔区九龙大道206号  学校办公室:020-82876130  招生电话:020-82872773'
a=re.search('(\d{3,4})-(\d{6,8})',tel).group(2)
print(a)

3. 用正则表达式进行英文分词。re.split('',news)

str='''Lee is on a five-day working visit to China starting Sunday, his second visit to China since September. During the visit, he will attend the Boao Forum for Asia's annual conference in Hainan. It will be his first time at the conference and he will deliver a speech at the opening session of the forum.'''
print(re.split("[\s,.?!]+",str))

4. 使用正则表达式取得新闻编号。

q='http://news.gzcc.cn/html/2017/xiaoyuanxinwen_0925/8249.html'
print(re.match('http://news.gzcc.cn/html/2017/xiaoyuanxinwen_(.*).html',q).group(1).split('/')[-1])
print(re.search('\_(.*).html',q).group(1).split('/')[-1])
print(re.findall('\_(.*).html',q)[-1].split('/')[-1])

5. 生成点击次数的Request URL

url='http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0404/9183.html'
a=re.match('http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0404/(.*).html',url).group(1)
srac='http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(a)
print(srac)

6. 获取点击次数

resc = requests.get(clickUrl)
    num = re.search(".html\('(\d*)'\)",resc.text).group(1)
    print(num)
getClickCount("http://news.gzcc.cn/html/2018/xiaoyuanxinwen_0404/9183.html");

7. 将456步骤定义成一个函数 def getClickCount(newsUrl):

8. 将获取新闻详情的代码定义成一个函数 def getNewDetail(newsUrl):

import requests
import re
from bs4 import BeautifulSoup
from datetime import datetime

def getClickCount(newUrl):
    newId=re.search('\_(.*).html',newUrl).group(1).split('/')[1]
    clickUrl='http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newId)
    return (int(requests.get(clickUrl).text.split('.html')[-1].lstrip("('").rstrip("');")))
def getNewDetail(url):
    res1 = requests.get(a)
    res1.encoding = 'utf-8'
    soup1 = BeautifulSoup(res1.text, 'html.parser')

    soup1.select('#content')[0].text  # 正文
    info = soup1.select('.show-info')[0].text
    d = info.lstrip('发布时间:')[:19] #发布日期和时间

    dt=datetime.strptime(d,'%Y-%m-%d %H:%M:%S')
    au=info[info.find('作者:'):].split()[0].lstrip('作者:') #作者
    clickCount=getClickCount(a)

newUrl="http://news.gzcc.cn/html/2017/xiaoyuanxinwen_0925/8249.html"
newId = re.search('\_(.*).html', newUrl).group(1).split('/')[1]
clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newId)
print(clickUrl,'\n',getClickCount(newUrl))

url='http://news.gzcc.cn/html/xiaoyuanxinwen/'
res=requests.get(url)
res.encoding="utf-8"
soup=BeautifulSoup(res.text,"html.parser")
for news in soup.select("li"):
    if len(news.select(".news-list-title")) > 0:
        t=news.select('.news-list-title')[0].text
        a = news.select('a')[0].attrs['href']  # 新闻链接
        print(t,a,'\n')
        getNewDetail(a)
        break

转载于:https://www.cnblogs.com/Lorz/p/8780828.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值