计算html文档中的单词

问题描述 投票:1回答:1

我想使用R计算html文章中的单词。像标题这样的刮擦数据很好,我能够下载文章(下面的代码)。现在我想计算所有这些文章中的单词,例如“Merkel”这个词。

这看起来有点复杂。我能够使它与标题一起工作(在1个向量中抛出每个标题并计算单词),但这太详细和太多的代码(因为我不得不手动将每个月的标题扔在一起,如果有超过1页结果在搜索)这就是为什么我不会在这里发布所有代码(我敢肯定它可以很容易,但那是另一个问题)。

我想我搞砸了一些东西,这就是为什么我不能对html文章做同样的事情。不同之处在于我直接删除了标题,但我必须首先下载html文件。

那么我怎么能通过我的10000(这里只有45个)html页面找一些漂亮的keywoards呢?一月的例子;我用这段代码下载文章;

library(xml2)
library(rvest)
url_parsed1 <- read_html("http://www.sueddeutsche.de/news?search=Fl%C3%BCchtlinge&sort=date&dep%5B%5D=politik&typ%5B%5D=article&sys%5B%5D=sz&catsz%5B%5D=alles&time=2015-01-01T00%3A00%2F2015-12-31T23%3A59&startDate=01.01.2015&endDate=31.01.2015")
link_nodes <- html_nodes(url_parsed1, css = ".entrylist__link")
html_links <- html_attr(link_nodes, "href")
getwd()
dir.create("html_articles")
setwd("html_articles")
for (url in html_links) {
 newName <- paste (basename(url),".html")
download.file(url, destfile = newName)
}

非常感谢你的帮助!

html r web-scraping
1个回答
0
投票

我希望我能正确理解你的问题:

library(xml2)
library(rvest)
library(XML)
url_parsed1 <- read_html("http://www.sueddeutsche.de/news?search=Fl%C3%BCchtlinge&sort=date&dep%5B%5D=politik&typ%5B%5D=article&sys%5B%5D=sz&catsz%5B%5D=alles&time=2015-01-01T00%3A00%2F2015-12-31T23%3A59&startDate=01.01.2015&endDate=31.01.2015")
link_nodes <- html_nodes(url_parsed1, css = ".entrylist__link")
html_links <- html_attr(link_nodes, "href")
getwd()
dir.create("html_articles")
setwd("html_articles")
for (url_org in html_links) { 
  # url_org <- html_links[1]
  newName <- paste (basename(url_org),".html")

  download.file(url_org, destfile = newName)
  # Read and parse HTML file
  doc.html <- htmlTreeParse(url_org,
                useInternal = TRUE)
  # Extract all the paragraphs (HTML tag is p, starting at
  # the root of the document). Unlist flattens the list to
  # create a character vector.
  doc.text = unlist(xpathApply(doc.html, '//p', xmlValue))
  # Replace all \n by spaces
  doc.text = gsub('\\n', ' ', doc.text)

  # Join all the elements of the character vector into a single
  # character string, separated by spaces
  doc.text = paste(doc.text, collapse = ' ')
  # count the occurences of the word "Merkel in that hmtl
  str_count(doc.text,"Merkel")
}

我想将学分传递给herehere

© www.soinside.com 2019 - 2024. All rights reserved.