【问题标题】:How to find the mean of words using R如何使用R找到单词的平均值
【发布时间】:2021-03-30 11:39:34
【问题描述】:

我是 R 新手,我正在尝试从包含图书列表的网站上抓取数据。我已经设法从网站上抓取了 20 个书名,我现在想在这个网站上找到书名的平均字长(所有字长的平均值)。但是我不确定如何使用 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) 

提前致谢。

【问题讨论】:

  • word_vec &lt;- c("Hello", "World"); mean(stringr::str_length(word_vec))
  • 如果您已经抓取了数据,那么您可能不需要在问题中包含 URL 抓取;如果您至少提供该抓取提供的数据样本,这可能会更容易(对我们而言)。所有r-tag 页面顶部的文本建议使用dput() 提供示例数据,因为它是明确的(控制台上的数据输出通常不是您认为的那样) .

标签: r web-scraping


【解决方案1】:

也许您可以将所有单词放在一个列表中,称之为“书籍”。那么:

values<-lapply(books,nchar)

最后:

mean(unlist(values))

【讨论】:

    【解决方案2】:

    我们也可以

    library(purrr)
    library(dplyr)
    map(books, nchar) %>%
        flatten_int %>%
         mean
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 2018-07-24
      • 2022-10-09
      • 2021-03-04
      • 2016-10-20
      • 2018-05-21
      • 1970-01-01
      相关资源
      最近更新 更多