如何在R中高效实现文本token匹配的累计打分功能 支持tidyverse方案
R语言tidyverse风格文本得分计算实现
实现思路
核心通过向量化的字符串匹配统计短语出现次数,乘以对应分值求和,完全避免手动for循环,执行效率远高于逐行遍历,适合大批量文本计算场景。
完整代码
# 加载tidyverse依赖 library(tidyverse) # 构造原始文本表 text_df <- tibble( text = c( "The quick brown fox jumped over the lazy dogs", "The cow jumped over the moon" ) ) # 构造分值查询表 lookup_df <- tibble( keyword = c("jumped", "over the", "cow"), value = c(2, -1, 2) ) # 核心得分计算 result <- text_df %>% rowwise() %>% mutate( score = sum( # ignore_case = TRUE 适配大小写不敏感的匹配需求,不需要可删除 str_count(text, regex(lookup_df$keyword, ignore_case = TRUE)) * lookup_df$value ) ) %>% ungroup()
输出结果
运行后得到的result完全匹配预期输出:
| text | score |
|---|---|
| The quick brown fox jumped over the lazy dogs | 1 |
| The cow jumped over the moon | 3 |
优化提示
- 如果关键词无需正则匹配,可将
regex替换为fixed,匹配速度提升30%以上:str_count(text, fixed(lookup_df$keyword, ignore_case = TRUE)) - 存在重叠关键词(如同时有"over"和"over the")时,可先对查询表按关键词长度降序排序,保证长关键词优先匹配:
lookup_df <- arrange(lookup_df, -str_length(keyword))
内容的提问来源于stack exchange,提问作者Christopher Penn
相关产品推荐
相关产品推荐

