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

如何将含指定分隔符的文本按括号内整数重组为R数据框

解决R向量转数据框并保留括号内数字与文本对应顺序的问题

问题描述

有一个名为chapt1的R向量,需要将其重组为数据框df1,要求:

  • 每个段落开头括号内的整数作为df1的第一列;
  • 相邻文本作为同一行的第二列;
  • 保持数字在原始字符串中出现的顺序,而非按数字大小排序。

原始向量:

chapt1 <- ("1. The Grand Opening (35) The black cat jumped over the 
lazy rabbit. (36) Salt has no taste (37) The grandmaster mentors his 
disciples   (1)   Generation of miracles.  (2)  Are we there yet: 
opening the first stage in the dungeon.")

期望结果:

35       The black cat jumped over the lazy rabbit.
36       Salt has no taste
37       The grandmaster mentors his disciples.
1        Generation of miracles.
2        Are we there yet: opening the first stage in the dungeon.

问题分析

你之前尝试的separate_rows方法会将数字和文本拆分为独立的行,无法直接建立数字与对应文本的配对关系,导致后续无法保证顺序一致。正确的思路是成对提取括号内的数字和其对应的后续文本,并保留原始出现顺序。

解决方案代码

使用tidyverse工具链实现:

library(tidyverse)

# 原始向量
chapt1 <- ("1. The Grand Opening (35) The black cat jumped over the 
lazy rabbit. (36) Salt has no taste (37) The grandmaster mentors his 
disciples   (1)   Generation of miracles.  (2)  Are we there yet: 
opening the first stage in the dungeon.")

# 处理流程
df1 <- tibble(text = chapt1) %>%
  # 提取所有"(数字) 文本"的配对片段,直到下一个"(数字)"或字符串结尾
  mutate(matches = str_extract_all(text, "\\((\\d+)\\)\\s*(.*?)(?=\\s*\\(\\d+\\)|$)")) %>%
  # 将提取的列表拆分为单独行
  unnest_longer(matches) %>%
  # 拆分数字部分和文本部分
  separate(matches, into = c("num", "content"), sep = "\\)\\s*", extra = "merge") %>%
  # 清理数据:去掉数字前的括号,转换为整数;清理文本的多余空格
  mutate(
    num = str_remove(num, "^\\(") %>% as.integer(),
    content = str_squish(content)
  ) %>%
  # 过滤掉开头无意义的空内容行(原始字符串开头的非目标文本)
  filter(content != "")

# 查看结果
print(df1, width = Inf)

代码说明

  1. str_extract_all:使用正则表达式\\((\\d+)\\)\\s*(.*?)(?=\\s*\\(\\d+\\)|$)精准提取每个括号数字及其对应的文本段,其中(?=\\s*\\(\\d+\\)|$)是正向预查,确保每个文本段截止到下一个括号数字或字符串结尾;
  2. unnest_longer:将提取的列表型数据拆分为每行一个配对片段;
  3. separate:将每个配对片段拆分为数字列和文本列,extra = "merge"保证文本中的空格不会被拆分;
  4. 数据清理:去掉数字前的括号并转为整数,用str_squish清理文本的多余空格、换行符;
  5. 过滤空行:去掉原始字符串开头不属于目标配对的内容行。

关键说明:保证顺序一致的核心

通过正向预查的正则提取,我们严格按照原始字符串中括号数字出现的顺序来提取对应的文本段,整个过程没有对数字进行排序,因此最终数据框的行顺序完全匹配原始字符串中数字的出现顺序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 22:01:16