You need to enable JavaScript to run this app. 如何在R中高效实现文本token匹配的累计打分功能 支持tidyverse方案
优惠活动
大模型
产品
解决方案
定价
更多

如何在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完全匹配预期输出:

textscore
The quick brown fox jumped over the lazy dogs1
The cow jumped over the moon3

优化提示

  • 如果关键词无需正则匹配,可将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 23:54:00