r - 如何查找我从 R 中的网站上抓取的书名中单词的频率
问题描述
我对 R 和网络抓取非常陌生。为了练习,我从网站上抓取书名,并使用这些书名计算出一些基本的统计数据。到目前为止,我已经设法刮掉书名,将它们添加到表格中,并找到书的平均长度。我现在想在书名中找到最常用的词,它可能是“the”,但我想用 R 来证明这一点。目前我的程序只查看完整的书名,我需要拆分单词变成了他们自己的个体身份,这样我就可以计算不同单词的数量。但是,我不知道该怎么做。
代码:
url <- 'http://books.toscrape.com/index.html'
bookNames <- read_html(allUrls) %>%
html_nodes(xpath='//*[contains(concat( " ", @class, " "), concat( " ", "product_pod", " " ))]//a') %>%
html_text
view(bookNames)
values<-lapply(bookNames,nchar)
mean(unlist(values))
bookNames<-tolower(bookNames)
sort(table(bookNames), decreasing=T)[1:2]
我认为将每个单词分成一个新列表可以解决我的问题,但我不知道该怎么做。提前致谢。
以上是我能够制作的书籍表。
解决方案
您可以通过以下方式获取所有书名:
library(rvest)
url <- 'http://books.toscrape.com/index.html'
url %>%
read_html() %>%
html_nodes('h3 a') %>%
html_attr('title') -> titles
titles
# [1] "A Light in the Attic"
# [2] "Tipping the Velvet"
# [3] "Soumission"
# [4] "Sharp Objects"
# [5] "Sapiens: A Brief History of Humankind"
# [6] "The Requiem Red"
# [7] "The Dirty Little Secrets of Getting Your Dream Job"
#....
要获得标题中最常用的单词,您可以将字符串拆分为空格并用于table
计算频率。
head(sort(table(tolower(unlist(strsplit(titles, '\\s+')))), decreasing = TRUE))
# the a of #1) and for
# 14 3 3 2 2 2