我有一些段落,对于每个段落,我都有不同的关键词。例如:
I am a student. I like machine learning...
这里我的关键词是学生和机器学习。我想给他们提供不同的颜色,例如学生用红色,机器学习用黄色。因此,结果应为:
我可以使用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)
在这里,结果是:
但是这似乎仅适用于名称实体。就我而言,我的关键字是我自己提取的。因此可能有所不同
如评论中所述,我前一段时间为此创建了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)
---
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)
```
该程序包是基于对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
进行简单替换的原因是,可以忽略大小写,而忽略其他正则表达式。