You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合首字母匹配与str_replace实现带国家标识的缩写替换?

解决方案

首先修正数据(原数据中country数组缺少最后一个"Malasia"),然后结合dplyr和stringr实现需求:

步骤1:加载依赖库与准备数据

library(dplyr)
library(stringr)

# 补全后的原始数据
country <- c("US", "UK", "Malasia", "Albania", "Poland", "Malasia")
abbr <- c("SP num1", "SP num1", "MSP num2", "ASD num1", "ASD num3", "first MSP num1")
words_to_replace <- c("SP", "SD")
replacements <- c("state police", "state duma")

# 构建替换规则的命名向量
replace_vec <- setNames(replacements, words_to_replace)

# 转换为数据框
df <- tibble(country = country, abbr = abbr)

步骤2:核心处理逻辑

通过逐行匹配「国家首字母+目标缩写」的模式,先替换带前缀的缩写,再处理普通缩写,最后统一转小写:

df_processed <- df %>%
  mutate(
    # 国家名转小写
    country_lower = str_to_lower(country),
    # 提取国家名首字母(大写)
    country_init = str_sub(str_to_upper(country), 1, 1),
    # 逐行处理缩写
    abbr_processed = pmap_chr(
      list(abbr, country_init, country_lower),
      function(ab, init, cl) {
        # 先处理带国家首字母的缩写(如 MSP → malasia state police)
        for (word in words_to_replace) {
          # 构建正则模式:匹配「首字母+目标缩写」作为独立单词
          pattern <- str_c("\\b", init, word, "\\b")
          ab <- str_replace_all(ab, pattern, str_c(cl, replace_vec[word]))
        }
        # 再处理普通独立缩写(如 SP → state police)
        ab <- str_replace_all(ab, replace_vec)
        # 统一转小写
        str_to_lower(ab)
      }
    ),
    # 国家列转小写
    country = country_lower
  ) %>%
  # 调整为期望的列名
  select(country, `新内容` = abbr_processed)

输出结果

运行后得到的结果与需求一致:

print(df_processed)
#> # A tibble: 6 × 2
#>   country  `新内容`                         
#>   <chr>    <chr>                            
#> 1 us       state police num1                
#> 2 uk       state police num1                
#> 3 malasia  malasia state police num2        
#> 4 albania  albania state duma num1          
#> 5 poland   asd num3                         
#> 6 malasia  first malasia state police num1

说明

  • 若不需要严格匹配「独立单词」(比如缩写出现在字符串中间无空格),可去掉正则中的\\b边界符
  • 若你的ASD实际应为ASP(匹配期望中的state police),只需调整原始abbr数组即可,代码逻辑无需改动

内容的提问来源于stack exchange,提问作者Polina Ermolaeva

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:32:48