前段时间在研究RCrul的爬虫技术时,要了解正则表达式的一些知识,在google发现一篇介绍利用正则表达式处理网上抓取下来处理数据的方法:
原文地址:http://r-ke.info/2012/05/28/regular-expression.html
但是原文代码不能直接编译,估计是俺看到的是国内豆瓣缘故导致。故将文章中的代码进行重新编译,现附上源代码,直接copy到R中能直接运行:
getcontent <- function(s,g){ substring(s,g,g+attr(g,'match.length')-1) } # getcontent(word[1],gregout[[1]]) # 获取网页原代码,以行的形式存放在web变量中(每页显示25条记录,共10页) url<-'http://movie.douban.com/top250?format=text' web <- readLines(url,encoding="UTF-8") for(i in 1:9){ url1<-paste('http://movie.douban.com/top250?start=',25*i,'&filter=&type=',sep="") web1 <- readLines(url1,encoding="UTF-8") web<-c(web,web1) } # 找到包含电影名称的行编号 name <- web[grep(' <div class="hd">',web)+2] # 用正则表达式来提取电影名 gregout <- gregexpr('>w+',name) movie.names = 0 for(i in 1:length(gregout)){ movie.names[i]<-getcontent(name[i],gregout[[i]]) } movie.names <- sub('>','',movie.names) # 找到包含电影发行年份的行编号并进行提取 # year <- web[grep('<br>',web)+1] # movie.year <- substr(year,28,32) year <- web[grep('<p class="">',web)+2] movie.year <- substr(year,32) # 找到包含电影评分的行编号并进行提取 score <- web[grep('<div class="star">',web)+1] movie.score<-NULL for(i in 1:length(score)) { score1<-gregexpr('<em>',score) movie.score<-cbind(movie.score,substr(score[i],score1[[i]][1]+4,score1[[i]][1]+6)) } # 找到包含电影评价数量的行编号并进行提取 rating <- web[grep('<div class="star">',web)+2] movie.rating<-NULL for(i in 1:length(rating)){ rating1<-gregexpr(' ',rating) rating2<-gregexpr('人',rating) movie.rating<-cbind(movie.rating,substr(rating[i],rating1[[i]][1]+12,rating2[[i]][1]-1)) } # 合成为数据框 movie <- data.frame(names=movie.names,year=as.numeric(movie.year), score=as.numeric(movie.score),rate=as.numeric(movie.rating))
head(movie)
names year score rate 1 肖申克的救赎 1994 9.6 559765 2 这个杀手不太冷 1994 9.4 529674 3 阿甘正传 1994 9.4 473569 4 霸王别姬 1993 9.4 377790 5 美丽人生 1997 9.4 258244 6 海上钢琴师 1998 9.2 41594 # 绘散点图 library(ggplot2) p <- ggplot(data=movie,aes(x=year,y=score)) p+geom_point(aes(size=rate),colour='lightskyblue4', position="jitter",alpha=0.8)
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|