【问题标题】:Remove only some line breaks in R仅删除 R 中的一些换行符
【发布时间】:2018-11-11 20:49:46
【问题描述】:

我正在将一个文本文件读入 R:

text <- read_delim("textfile.txt", "\n", escape_double = F, col_names = F, trim_ws = T)

相关部分是它由换行符分隔。 然后我把它分成speaker列和cmets列:

    text2 <- text %>%
  separate(X1, into = c("speaker", "comment"), sep = ":")

结果是一个数据框,其中有一列发言者和另一列他们的 cmets。

问题在于,一些长 cmets 中嵌入了换行符。这会弄乱数据结构,将评论放在扬声器列中的换行符之后,然后在 cmets 部分中放置一个 NA。

如何告诉 R 忽略这些嵌入的换行符?如果有帮助,则用冒号分隔各列(即面试官:你好吗?),因此“真”换行符之前应该只有一个冒号。

谢谢!

【问题讨论】:

  • 你能发布几个你输入的例子吗
  • 是否可以改变textfile.txt的输出格式? (可能不会,但值得一试)

标签: r text delimiter data-cleaning


【解决方案1】:

我将假设您的输入文件如下所示:

文本文件.txt

Interviewer: How are you?
Respondant: I'm fine.
Interviewer: The issue is that some of the long comments have line breaks
embedded in them. This messes up the data structure putting the comment after
the line break in the speaker column and then an NA in the comments section.
Respondant: How can I tell R to ignore these embedded line breaks? If it helps,
the columns are separated by a colon (i.e. Interviewer: How are you?), so there
should be only one colon before the "true" line break.

如果是这样,这个过程应该可以工作:

  1. 将线条读入矢量。
  2. 找出以演讲者姓名开头的行。
  3. 根据它们位于“起始”行之间的位置对所有行进行分类。
  4. 将 cmets 组合成块。
  5. 提取每个评论块的发言人姓名。
  6. data_frame它。

library(stringi)
library(dplyr)

text <- readLines("textfile.txt")
speaker_pattern <- "^\\w+(?=:)"
comment_starts <- which(stri_detect_regex(text, speaker_pattern))
comment_groups <- findInterval(seq_along(text), comment_starts)
comments <- text %>%
  split(comment_groups) %>%
  vapply(FUN = paste0, FUN.VALUE = character(1), collapse = "\n")
speakers <- stri_extract_first_regex(comments, speaker_pattern)
comments <- stri_replace_first_regex(comments, "^\\w+: ", "")
text2 <- data_frame(speaker = speakers, comment = comments)

text2
# # A tibble: 4 x 2
#   speaker     comment                                            
#   <chr>       <chr>                                              
# 1 Interviewer How are you?                                       
# 2 Respondant  I'm fine.                                          
# 3 Interviewer "The issue is that some of the long comments have ~
# 4 Respondant  "How can I tell R to ignore these embedded line br~

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-26
    • 2015-04-24
    • 2014-10-17
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多