【问题标题】:Cumulative Word Count using R使用 R 的累积字数
【发布时间】:2015-11-06 19:21:56
【问题描述】:

有没有办法获得文本的累积字数?我有一个要分析的文本,我想找到文本中总单词的累积计数以及文本中某些单词的累积计数。

目前我有 3 个单独的数据框。第一个包含文本文档中的所有单词,一个“计数”列,其中包含一直向下的 1,以及一个“总计”列,它给出了“计数”列的累积总和。其他两个数据框完全相同,只是它们只包含我在文本中查找的特定单词的所有出现。

我们的目标是制作一个图,显示整个文本中两个特定单词的使用关系。

感谢任何帮助。以下是我目前所拥有的。

URL <- 'http://shakespeare.mit.edu/romeo_juliet/full.html'
romeo <- htmlParse(URL)
txPath <- "//blockquote//a"
txValue <- xpathApply(romeo, txPath, xmlValue)
txValue <- strsplit(gsub('\\n','',txValue), split="  ")

words <- unlist(str_extract_all(txValue,'(\\w+)\'*(\\w+)'))
vWord <- tolower(words)
rCount <- unlist(str_extract_all(vWord,'(romeo)'))
lCount <- unlist(str_extract_all(vWord,'(love)'))

rDF <- as.data.frame(rCount) %>%
  mutate(count=1) %>%
  mutate(tot=cumsum(count))
lDF <- as.data.frame(lCount) %>%
  mutate(count=1) %>%
  mutate(tot=cumsum(count))
wordsDF <- as.data.frame(vWord) %>%
  mutate(count=1) %>%
  mutate(tot=cumsum(count))

【问题讨论】:

  • 你能告诉我们你到目前为止所做的尝试吗?
  • 当然,我编辑了帖子以包含我的代码。

标签: r rvest


【解决方案1】:

这显示了如何使用stringi(比内置字符串操作更快、更灵活)进行语料库切片和切块,以及一种绘制您正在寻找的比较的方法:

library(xml2)
library(rvest)
library(dplyr)
library(stringi)
library(ggplot2)

URL <- 'http://shakespeare.mit.edu/romeo_juliet/full.html'
wherefore <- read_html(URL)

txt <- stri_trim(html_text(html_nodes(wtxtherefore, "blockquote > a")))

corpus <- data_frame(word=stri_trans_tolower(unlist(stri_extract_all_words(txt))),
                     count=1)
corpus$word_number <- 1:nrow(corpus)

cumsum_corpus <- mutate(group_by(corpus, word), cumsum=cumsum(count))

gg <- ggplot(filter(cumsum_corpus, word %in% c("romeo", "juliet")),
             aes(x=word_number, y=cumsum))
gg <- gg + geom_line(aes(color=word), size=0.75)
gg <- gg + geom_point(aes(fill=word), shape=21, color="white", size=1.5)
gg <- gg + scale_x_continuous(limits=c(1, nrow(corpus)))
gg <- gg + theme_bw()
gg

【讨论】:

  • 谢谢,这正是我想要的
【解决方案2】:

如果您包含您的数据和所需的输出,将会有所帮助。但根据我的理解,你能不能用你的“第一个”data.frame 来做一些事情,比如(通过dplyr):

我对你的“第一个”data.frame 的看法:

df <- data.frame(word = c("a", "b", "c", "a", "a", "c", "d", "b", "a"),
                 count = rep(1,9))

library(dplyr)
df %>% group_by(word) %>% mutate(cumsum= cumsum(count))

输出:

    word count cumsum
      (fctr) (dbl)  (dbl)
    1      a     1      1
    2      b     1      1
    3      c     1      1
    4      a     1      2
    5      a     1      3
    6      c     1      2
    7      d     1      1
    8      b     1      2
    9      a     1      4

而且,因为我需要强迫自己学习data.table,所以这里有一个使用它的解决方案:

 library(data.table)
 setDT(df)[, cumsum:=cumsum(count), by=word]

【讨论】:

  • 谢谢,我一定要试试。我还编辑了我的帖子以包含我的代码。
猜你喜欢
  • 2014-09-29
  • 2013-06-19
  • 2016-02-19
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
  • 1970-01-01
  • 2021-03-19
  • 1970-01-01
相关资源
最近更新 更多