我可以使用R突出显示段落中某些单词的背景颜色吗?

时间:2019-11-18 22:41:06

标签: r text background-color keyword

我有一些段落,每个段落都有不同的关键词。例如:

I am a student. I like machine learning...

在这里,我的关键词是学生和机器学习。我想给他们提供不同的颜色,例如学生用红色,机器学习用黄色。因此,结果应为:

enter image description here

我可以使用R来做到这一点吗?

此外,我知道Python可以以某种方式做到这一点。例如:

from spacy import displacy

doc = nlp('I just bought 2 shares at 9 a.m. because the stock went up 30% in just 2 days according to the WSJ')
displacy.render(doc, style='ent', jupyter=True)

在这里,结果是:

enter image description here

但是,这似乎仅适用于名称实体。就我而言,我的关键字是我自己提取的。所以可能会有所不同

1 个答案:

答案 0 :(得分:2)

如评论中所述,我前段时间为此创建了a small package。它仍处于实验阶段,目前只能在RMarkdown中使用,否则将在交互使用时打开浏览器窗口(Rstudio中的Viewer Pane)以显示文本。

# devtools::install_github("JBGruber/highlightr")
library(highlightr)
text <- "I am a student. I like machine learning..."
df <- data.frame(
  feature = c("student", "machine learning"),
  bg_colour = c("red", "yellow"),
  stringsAsFactors = FALSE
)
dict <- as_dict(df)
highlight(text, dict)

enter image description here

---
output: html_document
---

```{r , results='asis'}
library(highlightr)
text <- "I am a student. I like machine learning..."
df <- data.frame(
  feature = c("student", "machine learning"),
  bg_colour = c("red", "yellow"),
  stringsAsFactors = FALSE
)
dict <- as_dict(df)
highlight(text, dict)
```

enter image description here

该程序包基于对html输出的一些非常直观的操作:

# bg_colour
for (j in seq_along(dict$feature)) {
  text[i] <- stringi::stri_replace_all_fixed(
    str = text[i],
    pattern = dict$feature[j],
    replacement = paste0("<span style='background-color: ",
                         dict$bg_colour[j], "'>",
                         dict$feature[j], "</span>"),
    opts_fixed = stringi::stri_opts_fixed(case_insensitive = case_insensitive)
  )
}

我在这里所做的就是在突出显示的单词之前添加<span style='background-color: yellow'>,并在该单词之后添加</span>。有时间的时候,我会为LaTeX输出做同样的事情,甚至更多。在此处使用stringi进行简单替换的原因是,可以在忽略其他正则表达式的情况下使用不区分大小写的字母。