【问题标题】:Visualize frequency of dictionary terms using quanteda使用 quanteda 可视化字典术语的频率
【发布时间】:2023-01-15 19:59:20
【问题描述】:

我正在分析几千篇报纸文章的文本,我想构建问题词典(例如医疗保健、税收、犯罪等)。每个字典词条都由几个术语组成(例如医生、护士、医院等)

作为诊断,我想看看哪些术语构成了每个词典类别的大部分。

该代码说明了我所在的位置。我已经找到了一种方法来分别打印每个字典条目的主要特征,但我希望最后有一个可以可视化的连贯数据框。

library(quanteda)
]# set path
path_data <- system.file("extdata/", package = "readtext")

# import csv file
dat_inaug <- read.csv(paste0(path_data, "/csv/inaugCorpus.csv"))
corp_inaug <- corpus(dat_inaug, text_field = "texts") 
  corp_inaug %>% 
tokens(., remove_punct = T) %>% 
  tokens_tolower() %>% 
  tokens_select(., pattern=stopwords("en"), selection="remove")->tok

#I have about eight or nine dictionaries 
dict<-dictionary(list(liberty=c("freedom", "free"), 
                      justice=c("justice", "law")))
#This producesa a dfm of all the individual terms making up the dictionary
tok %>% 
tokens_select(pattern=dict) %>% 
  dfm() %>% 
  topfeatures()
  
#This produces the top features just making up the 'justice' dictionary entry
tok %>% 
  tokens_select(pattern=dict['justice']) %>% 
  dfm() %>% 
  topfeatures()
#This gets me close to what I want, but I can't figure out how to collapse this now 
#to visualize which are the most frequent terms that are making up each dictionary category

dict %>% 
  map(., function(x) tokens_select(tok, pattern=x)) %>% 
  map(., dfm) %>% 
map(., topfeatures) 

【问题讨论】:

  • 为了帮助人们帮助您,请提供可用于运行示例的可重现数据示例。一种方法是加载数据并使用 dput(dat_inaug)。

标签: r quanteda


【解决方案1】:

我整理了代码并使用 data_corpus_inaugural 作为示例。这显示了如何通过字典键获取频率 data.frame,用于每个键中字典值的选定匹配项。

library("quanteda")
#> Package version: 3.2.4
#> Unicode version: 14.0
#> ICU version: 70.1
#> Parallel computing: 10 of 10 threads used.
#> See https://quanteda.io for tutorials and examples.
library("quanteda.textstats")

toks <- data_corpus_inaugural %>% 
  tokens(remove_punct = TRUE) %>% 
  tokens_tolower() %>% 
  tokens_remove(pattern = stopwords("en"))

dict <- dictionary(list(liberty = c("freedom", "free"), 
                        justice = c("justice", "law")))

dfmat_list <- lapply(names(dict), function(x) {
  tokens_select(toks, dict[x]) %>%
    dfm() %>%
    textstat_frequency() %>%
    cbind(data.frame(dict_key = x), .)
})

do.call(rbind, dfmat_list)
#>    dict_key feature frequency rank docfreq group
#> 1   liberty freedom       185    1      36   all
#> 2   liberty    free       183    2      49   all
#> 11  justice justice       142    1      47   all
#> 21  justice     law       129    2      38   all

创建于 2023-01-15 reprex v2.0.2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多