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

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

    def writeNewsDetail(newid,content):
        f=open(newid+'.txt','a',encoding='utf-8')
        f.write(content)
        f.close()

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

    • 单条新闻的详情-->字典news
    • 一个列表页所有单条新闻汇总-->列表newsls.append(news)
    • 所有列表页的所有新闻汇总列表newstotal.extend(newsls)
      import re
      import requests
      from bs4 import BeautifulSoup
      from datetime import datetime
      def getClickCount(newsUrl):
          newId=re.search("/(d*).html$",newsUrl).group(1)
          clickUrl ="http://oa.gzcc.cn/api.php?op=count&id={}&modelid=80".format(newId)
          resc = requests.get(clickUrl)
          num = re.search(".html('(d*)')",resc.text).group(1)
          return int(num,10)
      def getNewDetail(newsUrl):
          res1 = requests.get(newsUrl)
          res1.encoding = 'utf-8'
          soup1 = BeautifulSoup(res1.text, 'html.parser')
          #标题
          title=soup1.select_one(".show-title").text
          # 正文
          content = soup1.select_one("#content").text
          info = soup1.select_one(".show-info").text
          # 发布时间
          time = datetime.strptime(info.lstrip("发布时间:")[:19], "%Y-%m-%d %H:%M:%S")
          # 作者
          author = info[info.find("作者:"):].split()[0].lstrip("作者:")
          # 来源
          x = info.find("来源:")
          if x >= 0:
              source = info[x:].split()[0].lstrip("来源:")
          else:
              source = ""
          # 摄影
          x = info.find("摄影:")
          if x >= 0:
              shot = info[x:].split()[0].lstrip("摄影:")
          else:
              shot = ""
          return {"title":title,"content":content,"time":time,"author":author,"source":source,"shot":shot,"count":getClickCount(newsUrl)}
      def getnewsls(newslsUrl):
          newsls=[];
          res = requests.get(newslsUrl)
          res.encoding='utf-8'
          soup = BeautifulSoup(res.text, 'html.parser')
          a = soup.select_one(".news-list").select("a")
          for i in a:
              url = i.attrs.get('href')
              newsls.append(getNewDetail(url))
          return newsls
      def getPageNum(newstotalUrl):
          res = requests.get(newstotalUrl)
          res.encoding = 'utf-8'
          soup = BeautifulSoup(res.text, 'html.parser')
          a = soup.select_one("#pages").select("a")[-2]
          return int(a.text,10)
      def getnewstotal(newstotalUrl):
          newstotal=[];
          pageNum=getPageNum(newstotalUrl)
          newstotal.extend(getnewsls(newstotalUrl))
          for i in range(2,pageNum+1):
              newstotal.extend(getnewsls("http://news.gzcc.cn/html/xiaoyuanxinwen/{}.html".format(i)))
          return newstotal
      
      newstotal=getnewstotal("http://news.gzcc.cn/html/xiaoyuanxinwen/")

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

    df = pandas.DataFrame(newsTotal)

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

    df.to_excel('newsData.xlsx')

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

    • 提取包含点击次数、标题、来源的前6行数据
    • 提取‘学校综合办’发布的,‘点击次数’超过3000的新闻。
    • 提取'国际学院'和'学生工作处'发布的新闻。
        print(df[['click', 'title', 'sources']].head(6))
      
        print(df[(df['click'] > 3000) & (df['sources'] == '学校综合办')])
      
        sou = ['国际学院', '学生工作处']
        print(df[df['sources'].isin(sou)])
  • 相关阅读:
    open stack总结
    Nginx操作命令
    Nginx 配置详解
    Linux 常用命令-- top
    CEPH 使用SSD日志盘+SATA数据盘, 随OSD数目递增对性能影响的递增测试
    MyCat水平分库
    MyCat垂直分库
    MyCat基本知识
    utf8mb4复杂昵称问题
    Power安装linux-BIG ENDIAN mysql编译安装
  • 原文地址:https://www.cnblogs.com/hehe2333/p/8857334.html
Copyright © 2011-2022 走看看