【问题标题】:Counting words in html documents计算 html 文档中的单词
【发布时间】:2018-01-03 14:35:34
【问题描述】:

我想使用 R 计算 html 文章中的单词。 像标题这样的抓取数据效果很好,我可以下载文章(下面的代码)。现在我想计算所有这些文章中的单词,例如“默克尔”这个词。

这似乎有点复杂。我能够使它与标题一起使用(将每个标题放入 1 个向量中并计算单词),但那太详细且代码太多(因为如果有超过1 页导致搜索),这就是为什么我不会在这里发布所有代码(我相信这很容易,但那是另一个问题)。

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

那么我怎样才能浏览我的 10000 个(这里只有 45 个)html 页面并寻找一些不错的关键字? 一月的例子; 我用这个代码下载文章;

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】:

    希望我正确理解了您的问题:

    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

    【讨论】:

    • 非常感谢,这已经很有帮助了!但是你为什么要把它扔进for循环呢?如果我们想检查一些单词,那将需要一次又一次地下载所有内容。现在最大的问题是浏览已经下载的文章。还有:代码对你有用吗?它计算标题(=1)中单词“merkel”的出现次数,而不是在整个 html 中,并且 url_org 仅包含一篇文章,因此我们需要另一个循环来遍历文件夹中的所有文章。我知道如何在 java 中做到这一点,但在 R...
    • " length(grep("Merkel", doc.text))" 似乎无法正常工作。 str_count(doc.text,"Merkel") 解决了这个问题。现在缺少一个循环来浏览文件夹并查看每个 html 文件并将金额添加到总和
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    相关资源
    最近更新 更多