如何在R中提取句子内最高排名类关键词的前后词并新增列
R实现方案
核心匹配逻辑完全对齐需求
整个处理过程严格遵循两个核心规则,避免出现匹配偏差:
- 只在当前句子所属Class对应的关键词列表里做匹配,列表的排列顺序就是关键词优先级,排在越靠前的关键词越先被匹配,找到第一个命中的就停止后续检查
- 匹配时自动剥离单词前后的标点(比如句尾的句号、感叹号),避免标点干扰匹配结果;提取邻词时自动判断位置是否越界,没有前置/后置词的单元格直接留空
可直接运行的实现代码
首先加载轻量字符串处理依赖:
library(stringr)
第一步:构造和输入完全一致的数据集,日常使用时直接把data.frame()部分替换为read.csv()的读取结果即可
input_df <- data.frame( Sentence = c( "Joe just joined Alice on the set.", "Alexis buys green apples", "Yesterday, two friends unite.", "Combination between x and y!" ), Class = c("B", "C", "A", "A") )
第二步:配置优先级关键词规则,列表名和Class值一一对应,向量内的关键词顺序就是优先级从高到低
keyword_rule <- list( A = c("unite", "combination", "together"), B = c("joined", "join", "merge"), C = c("buy", "buys", "bought") )
第三步:定义邻词提取的核心处理函数
extract_adjacent <- function(sentence, class_label, rule) { # 获取当前类别的优先级关键词 target_kw <- rule[[class_label]] # 拆分句子为词序列:保留原文内容用于邻词提取,生成去标点、小写化的版本用于匹配 raw_words <- str_split(sentence, "\\s+")[[1]] clean_words <- str_to_lower(str_replace_all(raw_words, "[[:punct:]]", "")) # 按优先级顺序查找第一个命中的关键词 hit_pos <- NA hit_kw <- NA for (kw in target_kw) { match <- which(clean_words == str_to_lower(kw)) if (length(match) > 0) { hit_kw <- kw hit_pos <- match[1] break } } # 无匹配时返回空值 if (is.na(hit_pos)) { return(data.frame(matched_kw = "", before_word = "", after_word = "")) } # 提取前后邻词,越界则留空 before <- ifelse(hit_pos > 1, raw_words[hit_pos - 1], "") after <- ifelse(hit_pos < length(raw_words), raw_words[hit_pos + 1], "") return(data.frame(matched_kw = hit_kw, before_word = before, after_word = after)) }
第四步:逐行处理全表,拼接最终输出,导出为CSV即可
# 逐行调用处理函数 adj_result <- do.call( rbind, lapply( 1:nrow(input_df), \(i) extract_adjacent(input_df$Sentence[i], input_df$Class[i], keyword_rule) ) ) # 合并原表和处理结果 final_df <- cbind(input_df, adj_result)
输出效果校验
运行后得到的最终表和需求要求的效果完全一致:
| Sentence | Class | matched_kw | before_word | after_word |
|---|---|---|---|---|
| Joe just joined Alice on the set. | B | joined | just | Alice |
| Alexis buys green apples | C | buys | Alexis | green |
| Yesterday, two friends unite. | A | unite | friends | |
| Combination between x and y! | A | combination | between |
几个关键场景的匹配校验点:
- 优先级规则生效:A类的两个句子优先匹配顺位更高的
unite,未命中才检查下一个顺位的combination - 单词级完全匹配:C类句子中
buy未完全匹配时,才会匹配顺位次高的buys,不会出现部分匹配导致的规则错位 - 越界自动留空:句子开头的匹配词无前置词、句尾的匹配词无后置词时,对应单元格自动留空
- 标点不干扰匹配:词尾附带的句号、感叹号会在匹配阶段自动剥离,不影响关键词识别
内容的提问来源于stack exchange,提问作者Liuk
相关产品推荐
相关产品推荐

