【发布时间】:2021-09-30 04:45:52
【问题描述】:
我一直在编写一些 R 代码。目的是收集一个有 50 页的网站部分中的单词的平均字长和其他统计信息。收集统计数据没有问题,而且很容易。然而,让我的代码收集超过 50 页的统计信息是困难的部分,它似乎只从第一页输出信息。看下面的代码,忽略可怜的缩进。
install.packages(c('tidytext', 'tidyverse'))
library(tidyverse)
library(tidytext)
library(rvest)
library(stringr)
websitePage <- read_html('http://books.toscrape.com/catalogue/page-1.html')
textSort <- websitePage %>%
html_nodes('.product_pod a') %>%
html_text()
for (page_result in seq(from = 1, to = 50, by = 1)) {
link = paste0('http://books.toscrape.com/catalogue/page-',page_result,'.html')
page = read_html(link)
# Creates a tibble
textSort.tbl <- tibble(text = textSort)
textSort.tidy <- textSort.tbl %>%
funnest_tokens(word, text)
}
# Finds the average word length
textSort.tidy %>%
map(nchar) %>%
map(mean)
# Finds the most common words
textSort.tidy %>%
count(word, sort = TRUE)
# Removes the stop words and then finds most common words
textSort.tidy %>%
anti_join(stop_words) %>%
count(word, sort = TRUE)
# Counts the number of times the word "Girl" is in the text
textSort.tidy %>%
count(word) %>%
filter(word == "Girl")
【问题讨论】:
-
只输出第一个还是最后一个?
标签: r web-scraping