首页 > 解决方案 > 使用 R 中的模式拆分字符串

问题描述

这个问题建立在我之前关于拆分和分组纯文本(按数据框中的章节分组文本)的问题的基础上?

在 Shree 的帮助下,我已经清理了大部分文档!已经能够从列表中创建两列 - 第一列是章节编号,第二列是属于该章节的文本,但我遇到了一些更混乱的文本。

这是我的数据的最坏情况示例:

                                               x
1                                     Chapter 1.
2                              Chapter one text.
3 Chapter one text. Chapter 2. Chapter two text.
4                              Chapter two text.
5                                     Chapter 3.
6                            Chapter three text.
7                            Chapter three text.
8                   Chapter 4. Chapter four text
9                             Chapter four text.

df <- structure(list(x = c("Chapter 1. ", "Chapter one text. ", "Chapter one text. Chapter 2. Chapter two text. ", 
                           "Chapter two text. ", "Chapter 3. ", "Chapter three text. ", "Chapter three text. ", 
                           "Chapter 4. Chapter four text ","Chapter four text. ")), 
                .Names = "x", class = "data.frame", row.names = c(NA, -9L))

我需要像这样构造它(章节编号,然后按 ID 顺序显示该章节的章节文本),以便我可以应用我之前帖子中的函数并干净地拆分它:

                       x
1           Chapter 1. 
2    Chapter one text. 
3     Chapter one text.
4            Chapter 2.
5    Chapter two text. 
6    Chapter two text. 
7           Chapter 3. 
8  Chapter three text. 
9  Chapter three text. 
10           Chapter 4.
11   Chapter four text 
12  Chapter four text. 

这似乎是一个简单的问题,我可以使用正则表达式拆分字符串以查找 Chapter # ("Chapter [0-9]"),然后使用类似的逻辑将其再次拆分以将章节和文本分成单独的行。str_split但是,在尝试使用, gsub,separate_rows函数进行了多次尝试后,我被困在这里。

任何帮助表示赞赏。

标签: rregextext-miningstrsplit

解决方案


我们可以通过在(这里,我们使用正则表达式环视来匹配点之后的空格 ( ) 之后的separate_rows空格进行拆分来使用。.\\s

library(tidyverse)
df %>% 
   separate_rows(x, sep="(?<=[.])\\s") %>% 
   filter(x!='')
#                  x
#1           Chapter 1.
#2    Chapter one text.
#3    Chapter one text.
#4           Chapter 2.
#5    Chapter two text.
#6    Chapter two text.
#7           Chapter 3.
#8  Chapter three text.
#9  Chapter three text.
#10          Chapter 4.
#11  Chapter four text 
#12  Chapter four text.

推荐阅读