zoukankan      html  css  js  c++  java
  • 数据结构化与保存


    1. 将新闻的正文内容保存到文本文件。

    2. 将新闻数据结构化为字典的列表:

    • 单条新闻的详情-->字典news
    • 一个列表页所有单条新闻汇总-->列表newsls.append(news)
    • 所有列表页的所有新闻汇总列表newstotal.extend(newsls)

    3. 安装pandas,用pandas.DataFrame(newstotal),创建一个DataFrame对象df.

    4. 通过df将提取的数据保存到csv或excel 文件。

    5. 用pandas提供的函数和方法进行数据分析:

    • 提取包含点击次数、标题、来源的前6行数据
    • 提取‘学校综合办’发布的,‘点击次数’超过3000的新闻。
    • 提取'国际学院'和'学生工作处'发布的新闻。
    # -*- coding : UTF-8 -*-
    # -*- author : onexiaofeng -*-
    import requests
    from bs4 import BeautifulSoup
    from datetime import datetime
    import re, pandas
    
    
    
    # 获取新闻点击次数
    def getNewsId(url):
        newsId = re.findall(r'\_(.*).html', url)[0][-4:]
        clickUrl = 'http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80'.format(newsId)
        clickRes = requests.get(clickUrl)
        # 利用正则表达式获取新闻点击次数
        clickCount = int(re.search("hits').html('(.*)');", clickRes.text).group(1))
        return clickCount
    
    #将新闻正文写进文件,不会被覆盖
    def writeNewsContentToFile(content):
        f=open('gzccNews.txt','a',encoding='utf-8')
        f.write(content)
        f.close()
    
    # 获取新闻细节
    def getNewsDetail(newsUrl):
        contentlist={}
        resd = requests.get(newsUrl)
        resd.encoding = 'utf-8'
        soupd = BeautifulSoup(resd.text, 'html.parser')
        newsDict = {}
        content = soupd.select('#content')[0].text
        writeNewsContentToFile(content)
    
    
        info = soupd.select('.show-info')[0].text
        newsDict['title'] = soupd.select('.show-title')[0].text
    
        # 识别时间格式
        date = re.search('(d{4}.d{2}.d{2}sd{2}.d{2}.d{2})', info).group(1)
        # 识别一个至三个数据
        if(info.find('作者:')>0):
            newsDict['author'] = re.search('作者:((.{2,4}s|.{2,4}、){1,3})', info).group(1)
        else:
            newsDict['author'] = 'none'
        if(info.find('审核:')>0):
            newsDict['check'] = re.search('审核:((.{2,4}s){1,3})', info).group(1)
        else:
            newsDict['check'] = 'none'
        if(info.find('来源:')>0):
            newsDict['sources'] = re.search('来源:(.*)s*摄|点', info).group(1)
        else:
            newsDict['sources'] = 'none'
        if (info.find('摄影:') > 0):
            newsDict['photo'] = re.search('摄影:(.*)s*点', info).group(1)
        else:
            newsDict['photo'] = 'none'
        # 用datetime将时间字符串转换为datetime类型
        newsDict['dateTime'] = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
    
        # 调用getNewsId()获取点击次数
        newsDict['click'] = getNewsId(newsUrl)
    
        return newsDict
    
    
    def getListPage(listUrl):
        res = requests.get(listUrl)
        res.encoding = 'utf-8'
        soup = BeautifulSoup(res.text, 'html.parser')
    
        for new in soup.select('li'):
            if len(new.select('.news-list-title')) > 0:
                title = new.select('.news-list-title')[0].text
                description = new.select('.news-list-description')[0].text
                newsUrl = new.select('a')[0]['href']
                List = []
                print('标题:{0}
    内容:{1}
    链接:{2}'.format(title, description, newsUrl))
                # 调用getNewsDetail()获取新闻详情
                dict = getNewsDetail(newsUrl)
                List.append(dict)
                total.extend(List)
    
    
    total = []
    listUrl = 'http://news.gzcc.cn/html/xiaoyuanxinwen/'
    getListPage(listUrl)
    res = requests.get(listUrl)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')
    listCount = int(soup.select('.a1')[0].text.rstrip(''))//10+1
    df = pandas.DataFrame(total)
    df.to_excel('newsresult.xlsx')
    print(df[['click','author','dateTime','sources']][(df['click']>3000)&(df['sources'] == u'学生处')])
    print(df[(df['click'] > 3000) & (df['sources'] == '学校综合办')])
    print(df[['click', 'author', 'sources']].head(6))
    news_info = ['国际学院', '学生工作处']
    print(df[df['sources'].isin(news_info)])

     基本老师说的都实现了,但是pandas的多条件筛选涉及到中文的话老是失败,也上网找,前面加了个u可是还是失败,希望能得到老师指正。

  • 相关阅读:
    并发编程3
    并发编程2
    4/23
    4/22
    并发编程1
    粘包问题
    Navicat12激活
    IDEA创建maven项目报错解决:Failed to create a Maven project: 'C:/Users/../IdeaProjects/../pom.xml' already e
    IDEA
    windows下查看端口运行情况--解决端口冲突问题
  • 原文地址:https://www.cnblogs.com/wxf2/p/8808259.html
Copyright © 2011-2022 走看看