首页 > 解决方案 > R:使用一组数据框/单词字典交叉检查文本文档

问题描述

刚接触 R 和编码,我还是个学生。我有一个文本文档,想对我已经清理的字典/df 集进行交叉检查,并将文档标记为它的根词。目标是交叉检查 Document1 与 dictionary1 以查看 document1 中是否有任何单词与字典中的单词匹配。如果是,则文档将根据其类别进行标记。该示例将如下所示:

Document1 <- "One simple text"
dictionary1 <- data.frame("Term"= c("teacher", "simple", "shoot", "text"))

if (strcmp(Document1, dictionary1)){
print('Success')
} else {
print('Failed')
}

我尝试使用此代码的结果将打印为“失败”,即使 Document1 中有匹配的单词“simple”和“text”。我该如何解决这个问题?我是否需要先在 document1 上进行strsplit,然后使用strcmp函数进行比较?提前感谢任何可以为此提供解决方案的人。为我糟糕的英语道歉。

标签: rdictionarytextclassification

解决方案


欢迎来到 SO,我们可以在 r 中的 data.frame 中编写大部分内容

library(tidyverse)

Document1 <- "One simple text"
dictionary1 <- data.frame("Term" = c("teacher", "simple", "shoot", "text"))


df_results <- dictionary1 %>%
  mutate(result = str_detect(string = Document1, pattern = Term))

df_results
#>      Term result
#> 1 teacher  FALSE
#> 2  simple   TRUE
#> 3   shoot  FALSE
#> 4    text   TRUE


if (any(df_results$result == TRUE)) {
  print("Sucess")
} else {
  print("Failure")
}
#> [1] "Sucess"

Document1 <- "Nothing Matters"
dictionary1 <- data.frame("Term" = c("teacher", "simple", "shoot", "text"))


df_results <- dictionary1 %>%
  mutate(result = str_detect(string = Document1, pattern = Term))

df_results
#>      Term result
#> 1 teacher  FALSE
#> 2  simple  FALSE
#> 3   shoot  FALSE
#> 4    text  FALSE


if (any(df_results$result == TRUE)) {
  print("Sucess")
} else {
  print("Failure")
}
#> [1] "Failure"

# Another way is using vectors

Document1 <- "simple right"
dictionary1 <- data.frame("Term" = c("teacher", "simple", "shoot", "text"))

result <- str_detect(string = Document1, pattern = dictionary1$Term)

result
#> [1] FALSE  TRUE FALSE FALSE

if (any(result == TRUE)) {
  print("Sucess")
} else {
  print("Failure")
}
#> [1] "Sucess"

reprex 包于 2020-06-11 创建(v0.3.0)


推荐阅读