热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

python实现爬虫统计学校BBS男女比例之数据处理(三)

这篇文章主要介绍了python实现爬虫统计学校BBS男女比例之数据处理,需要的朋友可以参考下
本文主要介绍了数据处理方面的内容,希望大家仔细阅读。

一、数据分析

得到了以下列字符串开头的文本数据,我们需要进行处理

二、回滚

我们需要对httperror的数据进行再处理

因为代码的原因,具体可见本系列文章(二),会导致文本里面同一个id连续出现几次httperror记录:

//httperror265001_266001.txt
265002 httperror
265002 httperror
265002 httperror
265002 httperror
265003 httperror
265003 httperror
265003 httperror
265003 httperror

所以我们在代码里要考虑这种情形,不能每一行的id都进行处理,是判断是否重复的id。

java里面有缓存方法可以避免频繁读取硬盘上的文件,python其实也有,可以见这篇文章。

def main():
  reload(sys)
  sys.setdefaultencoding('utf-8')
  global sexRe,timeRe,notexistRe,url1,url2,file1,file2,file3,file4,startNum,endNum,file5
  sexRe = re.compile(u'em>\u6027\u522b(.*&#63;)\u4e0a\u6b21\u6d3b\u52a8\u65f6\u95f4(.*&#63;))\u62b1\u6b49\uff0c\u60a8\u6307\u5b9a\u7684\u7528\u6237\u7a7a\u95f4\u4e0d\u5b58\u5728<')
  url1 = 'http://rs.xidian.edu.cn/home.php&#63;mod=space&uid=%s'
  url2 = 'http://rs.xidian.edu.cn/home.php&#63;mod=space&uid=%s&do=profile'
  file1 = 'ruisi\\correct_re.txt'
  file2 = 'ruisi\\errTime_re.txt'
  file3 = 'ruisi\\notexist_re.txt'
  file4 = 'ruisi\\unkownsex_re.txt'
  file5 = 'ruisi\\httperror_re.txt'

  #遍历文件夹里面以httperror开头的文本
  for filename in os.listdir(r'E:\pythonProject\ruisi'):
    if filename.startswith('httperror'):
      count = 0
      newName = 'E:\\pythonProject\\ruisi\\%s' % (filename)
      readFile = open(newName,'r')
      oldLine = '0'
      for line in readFile:
        #newLine 用来比较是否是重复的id
        newLine = line
        if (newLine != oldLine):
          nu = newLine.split()[0]
          oldLine = newLine
          count += 1
          searchWeb((int(nu),))
      print "%s deal %s lines" %(filename, count)

本代码为了简便,没有再把httperror的那些id分类,直接存储为下面这5个文件里

 file1 = 'ruisi\\correct_re.txt'
  file2 = 'ruisi\\errTime_re.txt'
  file3 = 'ruisi\\notexist_re.txt'
  file4 = 'ruisi\\unkownsex_re.txt'
  file5 = 'ruisi\\httperror_re.txt'

可以看下输出Log记录,总共处理了多少个httperror的数据。

"D:\Program Files\Python27\python.exe" E:/pythonProject/webCrawler/reload.py
httperror132001-133001.txt deal 21 lines
httperror2001-3001.txt deal 4 lines
httperror251001-252001.txt deal 5 lines
httperror254001-255001.txt deal 1 lines

三、单线程统计unkownsex 数据

代码简单,我们利用单线程统计一下unkownsex(由于权限原因无法获取、或者该用户没有填写)的用户。另外,经过我们检查,没有性别的用户也是没有活动时间的。

数据格式如下:

253042 unkownsex
253087 unkownsex
253102 unkownsex
253118 unkownsex
253125 unkownsex
253136 unkownsex
253161 unkownsex

import os,time
sumCount = 0

startTime = time.clock()

for filename in os.listdir(r'E:\pythonProject\ruisi'):
  if filename.startswith('unkownsex'):
    count = 0
    newName = 'E:\\pythonProject\\ruisi\\%s' % (filename)
    readFile = open(newName,'r')
    for line in open(newName):
      count += 1
      sumCount +=1
    print "%s deal %s lines" %(filename, count)
print '%s unkowns sex' %(sumCount)

endTime = time.clock()
print "cost time " + str(endTime - startTime) + " s"

处理速度很快,输出如下:

unkownsex1-1001.txt deal 204 lines
unkownsex100001-101001.txt deal 50 lines
unkownsex10001-11001.txt deal 206 lines
#...省略中间输出信息
unkownsex99001-100001.txt deal 56 lines
unkownsex_re.txt deal 1085 lines
14223 unkowns sex
cost time 0.0813142301261 s

四、单线程统计 correct 数据

数据格式如下:

31024 男 2014-11-11 13:20
31283 男 2013-3-25 19:41
31340 保密 2015-2-2 15:17
31427 保密 2014-8-10 09:17
31475 保密 2013-7-2 08:59
31554 保密 2014-10-17 17:02
31621 男 2015-5-16 19:27
31872 保密 2015-1-11 16:49
31915 保密 2014-5-4 11:01
31997 保密 2015-5-16 20:14

代码如下,实现思路就是一行一行读取,利用line.split()获取性别信息。sumCount 是统计一个多少人,boycount 、girlcount 、secretcount 分别统计男、女、保密的人数。我们还是利用unicode进行正则匹配。

import os,sys,time
reload(sys)
sys.setdefaultencoding('utf-8')
startTime = time.clock()
sumCount = 0
boycount = 0
girlcount = 0
secretcount = 0
for filename in os.listdir(r'E:\pythonProject\ruisi'):
  if filename.startswith('correct'):
    newName = 'E:\\pythonProject\\ruisi\\%s' % (filename)
    readFile = open(newName,'r')
    for line in readFile:
      sexInfo = line.split()[1]
      sumCount +=1
      if sexInfo == u'\u7537' :
        boycount += 1
      elif sexInfo == u'\u5973':
        girlcount +=1
      elif sexInfo == u'\u4fdd\u5bc6':
        secretcount +=1
    print "until %s, sum is %s boys; %s girls; %s secret;" %(filename, boycount,girlcount,secretcount)
print "total is %s; %s boys; %s girls; %s secret;" %(sumCount, boycount,girlcount,secretcount)
endTime = time.clock()
print "cost time " + str(endTime - startTime) + " s"

注意,我们输出的是截止某个文件的统计信息,而不是单个文件的统计情况。输出结果如下:

until correct1-1001.txt, sum is 110 boys; 7 girls; 414 secret;
until correct100001-101001.txt, sum is 125 boys; 13 girls; 542 secret;
#...省略
until correct99001-100001.txt, sum is 11070 boys; 3113 girls; 26636 secret;
until correct_re.txt, sum is 13937 boys; 4007 girls; 28941 secret;
total is 46885; 13937 boys; 4007 girls; 28941 secret;
cost time 3.60047888495 s

五、多线程统计数据

为了更快统计,我们可以利用多线程。
作为对比,我们试下单线程需要的时间。

# encoding: UTF-8
import threading
import time,os,sys

#全局变量
SUM = 0
BOY = 0
GIRL = 0
SECRET = 0
NUM =0

#本来继承自threading.Thread,覆盖run()方法,用start()启动线程
#这和java里面很像
class StaFileList(threading.Thread):
  #文本名称列表
  fileList = []

  def __init__(self, fileList):
    threading.Thread.__init__(self)
    self.fileList = fileList

  def run(self):
    global SUM, BOY, GIRL, SECRET
    #可以加上个耗时时间,这样多线程更加明显,而不是顺序的thread-1,2,3
    #time.sleep(1)
    #acquire获取锁
    if mutex.acquire(1):
      self.staFiles(self.fileList)
      #release释放锁
      mutex.release()

  #处理输入的files列表,统计男女人数
  #注意这儿数据同步问题,global使用全局变量
  def staFiles(self, files):
    global SUM, BOY, GIRL, SECRET
    for name in files:
      newName = 'E:\\pythonProject\\ruisi\\%s' % (name)
      readFile = open(newName,'r')
      for line in readFile:
        sexInfo = line.split()[1]
        SUM +=1
        if sexInfo == u'\u7537' :
          BOY += 1
        elif sexInfo == u'\u5973':
          GIRL +=1
        elif sexInfo == u'\u4fdd\u5bc6':
          SECRET +=1
      # print "thread %s, until %s, total is %s; %s boys; %s girls;" \
      #    " %s secret;" %(self.name, name, SUM, BOY,GIRL,SECRET)


def test():
  #files保存多个文件,可以设定一个线程处理多少个文件
  files = []

  #用来保存所有的线程,方便最后主线程等待所以子线程结束
  staThreads = []
  i = 0
  for filename in os.listdir(r'E:\pythonProject\ruisi'):
    #没获取10个文本,就创建一个线程
    if filename.startswith('correct'):
      files.append(filename)
      i+=1
      #一个线程处理20个文件
      if i == 20 :
        staThreads.append(StaFileList(files))
        files = []
        i = 0
  #最后剩余的files,很可能长度不足10个
  if files:
    staThreads.append(StaFileList(files))

  for t in staThreads:
    t.start()
  # 主线程中等待所有子线程退出,如果不加这个,速度更快些?
  for t in staThreads:
    t.join()



if __name__ == '__main__':
  reload(sys)
  sys.setdefaultencoding('utf-8')
  startTime = time.clock()
  mutex = threading.Lock()
  test()
  print "Multi Thread, total is %s; %s boys; %s girls; %s secret;" %(SUM, BOY,GIRL,SECRET)
  endTime = time.clock()
  print "cost time " + str(endTime - startTime) + " s"

输出

Multi Thread, total is 46885; 13937 boys; 4007 girls; 28941 secret;
cost time 0.132137192794 s

我们发现时间和单线程差不多。因为这儿涉及到线程同步问题,获取锁和释放锁都是需要时间开销的,线程间切换保存中断和恢复中断也都是需要时间开销的。

六、较多数据的单线程和多线程对比

我们可以对correct、errTime 、unkownsex的文本都进行处理。
单线程代码

# coding=utf-8
import os,sys,time
reload(sys)
sys.setdefaultencoding('utf-8')
startTime = time.clock()
sumCount = 0
boycount = 0
girlcount = 0
secretcount = 0
unkowncount = 0
for filename in os.listdir(r'E:\pythonProject\ruisi'):
  # 有性别、活动时间
  if filename.startswith('correct') :
    newName = 'E:\\pythonProject\\ruisi\\%s' % (filename)
    readFile = open(newName,'r')
    for line in readFile:
      sexInfo =line.split()[1]
      sumCount +=1
      if sexInfo == u'\u7537' :
        boycount += 1
      elif sexInfo == u'\u5973':
        girlcount +=1
      elif sexInfo == u'\u4fdd\u5bc6':
        secretcount +=1
    # print "until %s, sum is %s boys; %s girls; %s secret;" %(filename, boycount,girlcount,secretcount)
  #没有活动时间,但是有性别
  elif filename.startswith("errTime"):
    newName = 'E:\\pythonProject\\ruisi\\%s' % (filename)
    readFile = open(newName,'r')
    for line in readFile:
      sexInfo =line.split()[1]
      sumCount +=1
      if sexInfo == u'\u7537' :
        boycount += 1
      elif sexInfo == u'\u5973':
        girlcount +=1
      elif sexInfo == u'\u4fdd\u5bc6':
        secretcount +=1
    # print "until %s, sum is %s boys; %s girls; %s secret;" %(filename, boycount,girlcount,secretcount)
  #没有性别,也没有时间,直接统计行数
  elif filename.startswith("unkownsex"):
    newName = 'E:\\pythonProject\\ruisi\\%s' % (filename)
    # count = len(open(newName,'rU').readlines())
    #对于大文件用循环方法,count 初始值为 -1 是为了应对空行的情况,最后+1得到0行
    count = -1
    for count, line in enumerate(open(newName, 'rU')):
      pass
    count += 1
    unkowncount += count
    sumCount += count
    # print "until %s, sum is %s unkownsex" %(filename, unkowncount)



print "Single Thread, total is %s; %s boys; %s girls; %s secret; %s unkownsex;" %(sumCount, boycount,girlcount,secretcount,unkowncount)
endTime = time.clock()
print "cost time " + str(endTime - startTime) + " s"

输出为

Single Thread, total is 61111; 13937 boys; 4009 girls; 28942 secret; 14223 unkownsex;
cost time 1.37444645628 s

多线程代码

__author__ = 'admin'
# encoding: UTF-8
#多线程处理程序
import threading
import time,os,sys

#全局变量
SUM = 0
BOY = 0
GIRL = 0
SECRET = 0
UNKOWN = 0

class StaFileList(threading.Thread):
  #文本名称列表
  fileList = []

  def __init__(self, fileList):
    threading.Thread.__init__(self)
    self.fileList = fileList

  def run(self):
    global SUM, BOY, GIRL, SECRET
    if mutex.acquire(1):
      self.staManyFiles(self.fileList)
      mutex.release()

  #处理输入的files列表,统计男女人数
  #注意这儿数据同步问题
  def staCorrectFiles(self, files):
    global SUM, BOY, GIRL, SECRET
    for name in files:
      newName = 'E:\\pythonProject\\ruisi\\%s' % (name)
      readFile = open(newName,'r')
      for line in readFile:
        sexInfo = line.split()[1]
        SUM +=1
        if sexInfo == u'\u7537' :
          BOY += 1
        elif sexInfo == u'\u5973':
          GIRL +=1
        elif sexInfo == u'\u4fdd\u5bc6':
          SECRET +=1
      # print "thread %s, until %s, total is %s; %s boys; %s girls;" \
      #    " %s secret;" %(self.name, name, SUM, BOY,GIRL,SECRET)

  def staManyFiles(self, files):
    global SUM, BOY, GIRL, SECRET,UNKOWN
    for name in files:
      if name.startswith('correct') :
        newName = 'E:\\pythonProject\\ruisi\\%s' % (name)
        readFile = open(newName,'r')
        for line in readFile:
          sexInfo = line.split()[1]
          SUM +=1
          if sexInfo == u'\u7537' :
            BOY += 1
          elif sexInfo == u'\u5973':
            GIRL +=1
          elif sexInfo == u'\u4fdd\u5bc6':
            SECRET +=1
        # print "thread %s, until %s, total is %s; %s boys; %s girls;" \
        #    " %s secret;" %(self.name, name, SUM, BOY,GIRL,SECRET)
      #没有活动时间,但是有性别
      elif name.startswith("errTime"):
        newName = 'E:\\pythonProject\\ruisi\\%s' % (name)
        readFile = open(newName,'r')
        for line in readFile:
          sexInfo = line.split()[1]
          SUM +=1
          if sexInfo == u'\u7537' :
            BOY += 1
          elif sexInfo == u'\u5973':
            GIRL +=1
          elif sexInfo == u'\u4fdd\u5bc6':
            SECRET +=1
        # print "thread %s, until %s, total is %s; %s boys; %s girls;" \
        #    " %s secret;" %(self.name, name, SUM, BOY,GIRL,SECRET)
      #没有性别,也没有时间,直接统计行数
      elif name.startswith("unkownsex"):
        newName = 'E:\\pythonProject\\ruisi\\%s' % (name)
        # count = len(open(newName,'rU').readlines())
        #对于大文件用循环方法,count 初始值为 -1 是为了应对空行的情况,最后+1得到0行
        count = -1
        for count, line in enumerate(open(newName, 'rU')):
          pass
        count += 1
        UNKOWN += count
        SUM += count
        # print "thread %s, until %s, total is %s; %s unkownsex" %(self.name, name, SUM, UNKOWN)


def test():
  files = []
  #用来保存所有的线程,方便最后主线程等待所以子线程结束
  staThreads = []
  i = 0
  for filename in os.listdir(r'E:\pythonProject\ruisi'):
    #没获取10个文本,就创建一个线程
    if filename.startswith("correct") or filename.startswith("errTime") or filename.startswith("unkownsex"):
      files.append(filename)
      i+=1
      if i == 20 :
        staThreads.append(StaFileList(files))
        files = []
        i = 0
  #最后剩余的files,很可能长度不足10个
  if files:
    staThreads.append(StaFileList(files))

  for t in staThreads:
    t.start()
  # 主线程中等待所有子线程退出
  for t in staThreads:
    t.join()



if __name__ == '__main__':
  reload(sys)
  sys.setdefaultencoding('utf-8')
  startTime = time.clock()
  mutex = threading.Lock()
  test()
  print "Multi Thread, total is %s; %s boys; %s girls; %s secret; %s unkownsex" %(SUM, BOY,GIRL,SECRET,UNKOWN)
  endTime = time.clock()
  print "cost time " + str(endTime - startTime) + " s"
  endTime = time.clock()
  print "cost time " + str(endTime - startTime) + " s"

输出为

Multi Thread, total is 61111; 13937 boys; 4009 girls; 28942 secret;
cost time 1.23049112201 s
可以看出多线程还是优于单线程的,由于使用的同步,数据统计是一直的。

注意python在类内部经常需要加上self,这点和java区别很大。

 def __init__(self, fileList):
    threading.Thread.__init__(self)
    self.fileList = fileList

  def run(self):
    global SUM, BOY, GIRL, SECRET
    if mutex.acquire(1):
      #调用类内部方法需要加self
      self.staFiles(self.fileList)
      mutex.release()

total is 61111; 13937 boys; 4009 girls; 28942 secret; 14223 unkownsex;
cost time 1.25413238673 s

以上就是本文的全部内容,希望对大家的学习有所帮助。

推荐阅读
  • 2018年人工智能大数据的爆发,学Java还是Python?
    本文介绍了2018年人工智能大数据的爆发以及学习Java和Python的相关知识。在人工智能和大数据时代,Java和Python这两门编程语言都很优秀且火爆。选择学习哪门语言要根据个人兴趣爱好来决定。Python是一门拥有简洁语法的高级编程语言,容易上手。其特色之一是强制使用空白符作为语句缩进,使得新手可以快速上手。目前,Python在人工智能领域有着广泛的应用。如果对Java、Python或大数据感兴趣,欢迎加入qq群458345782。 ... [详细]
  • 如何实现织梦DedeCms全站伪静态
    本文介绍了如何通过修改织梦DedeCms源代码来实现全站伪静态,以提高管理和SEO效果。全站伪静态可以避免重复URL的问题,同时通过使用mod_rewrite伪静态模块和.htaccess正则表达式,可以更好地适应搜索引擎的需求。文章还提到了一些相关的技术和工具,如Ubuntu、qt编程、tomcat端口、爬虫、php request根目录等。 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • PHP玩家基地系统毕业设计(附源码、运行环境)的用户登录界面、游戏管理和玩家作品管理
    本文介绍了一个PHP玩家基地系统的毕业设计,包括用户登录界面、游戏管理和玩家作品管理等功能。附带源码和运行环境,并提供免费赠送本源代码和数据库的方式,请私信获取详细信息。摘要共计约XXX字。 ... [详细]
  • Monkey《大话移动——Android与iOS应用测试指南》的预购信息发布啦!
    Monkey《大话移动——Android与iOS应用测试指南》的预购信息已经发布,可以在京东和当当网进行预购。感谢几位大牛给出的书评,并呼吁大家的支持。明天京东的链接也将发布。 ... [详细]
  • 本文介绍了《中秋夜作》的翻译及原文赏析,以及诗人当代钱钟书的背景和特点。通过对诗歌的解读,揭示了其中蕴含的情感和意境。 ... [详细]
  • 安装mysqlclient失败解决办法
    本文介绍了在MAC系统中,使用django使用mysql数据库报错的解决办法。通过源码安装mysqlclient或将mysql_config添加到系统环境变量中,可以解决安装mysqlclient失败的问题。同时,还介绍了查看mysql安装路径和使配置文件生效的方法。 ... [详细]
  • 本文详细介绍了SQL日志收缩的方法,包括截断日志和删除不需要的旧日志记录。通过备份日志和使用DBCC SHRINKFILE命令可以实现日志的收缩。同时,还介绍了截断日志的原理和注意事项,包括不能截断事务日志的活动部分和MinLSN的确定方法。通过本文的方法,可以有效减小逻辑日志的大小,提高数据库的性能。 ... [详细]
  • GetWindowLong函数
    今天在看一个代码里头写了GetWindowLong(hwnd,0),我当时就有点费解,靠,上网搜索函数原型说明,死活找不到第 ... [详细]
  • 本文描述了作者第一次参加比赛的经历和感受。作者是小学六年级时参加比赛的唯一选手,感到有些紧张。在比赛期间,作者与学长学姐一起用餐,在比赛题目中遇到了一些困难,但最终成功解决。作者还尝试了一款游戏,在回程的路上感到晕车。最终,作者以110分的成绩取得了省一会的资格,并坚定了继续学习的决心。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
author-avatar
别想着摆脱_525
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有