【问题标题】:R - find/replace line breaks using regexR - 使用正则表达式查找/替换换行符
【发布时间】:2019-08-16 03:30:18
【问题描述】:

我正在尝试使用正则表达式清理文件夹中的一堆 .txt 文件。我似乎无法让 R 找到换行符。

这是我正在使用的代码。它适用于字符替换,但不适用于换行符。

gsub_dir(dir = "folder_name", pattern = "\\n", replacement = "#")

我也尝试过 \r 和其他各种排列。使用纯文本编辑器,我发现所有换行符都带有 \n。

【问题讨论】:

  • 其实我觉得你会需要"\\\n",但是很难测试。
  • 可能是这样的(我没用过cat)。 test<-paste("This is a \n","test") test gsub("\\\n","",test)。虽然在这种情况下使用"\\n" 可能没有什么不同。
  • fortunes::fortune(365) 如有疑问,请继续添加斜杠,直到可行为止。
  • 如果您使用 fixed = TRUE 参数,您还可能会看到显着的加速。您实际上并不需要 regex,您只是在寻找完全匹配。
  • "\\\n" 不起作用;你说得对,这个例子我不需要 regex 但我确实需要 regex + 项目的换行符。

标签: r regex


【解决方案1】:

xfun::gsub_dir 无法做到这一点。

看看source code

  • 使用基本上执行x = readLines(con, encoding = 'UTF-8', warn = FALSE)read_utf8读入文件,
  • 然后,gsub 被输入这些行,当所有替换完成后,
  • write_utf8 function 将各行...与 LF、换行符、符号连接起来。

您需要为此使用一些自定义函数,这里是“快速而肮脏”的函数,它将用 # 替换所有 LF 符号:

lbr_change_gsub_dir = function(newline = '\n', encoding = 'UTF-8', dir = '.', recursive = TRUE) {
 files = list.files(dir, full.names = TRUE, recursive = recursive)
 for (f in files) {
   x = readLines(f, encoding = encoding, warn = FALSE)
   cat(x, sep = newline, file = f)
 }
}

folder <- "C:\\MyFolder\\Here"
lbr_change_gsub_dir(newline="#", dir=folder)

如果您希望能够匹配多行模式,请将pastecollapenewline 匹配并使用您喜欢的任何模式:

lbr_gsub_dir = function(pattern, replacement, perl = TRUE, newline = '\n', encoding = 'UTF-8', dir = '.', recursive = TRUE) {
 files = list.files(dir, full.names = TRUE, recursive = recursive)
 for (f in files) {
   x <- readLines(f, encoding = encoding, warn = FALSE)
   x <- paste(x, collapse = newline)
   x <- gsub(pattern, replacement, x, perl = perl)
   cat(x, file = f)
 }
}

folder <- "C:\\1"
lbr_gsub_dir("(?m)\\d+\\R(.+)", "\\1", dir = folder)

这将删除仅数字行之后的行。

【讨论】:

  • 谢谢——这可以回答我的狭隘问题。我仍然无法弄清楚我更广泛的问题,即如何使用正则表达式,包括文本文件文件夹上的换行符。我将发布一个关于此的新问题。
  • @WillHanley 请注意,您只需要paste 行。查看更新的答案。
  • 我仍然不确定如何做我想做的事--发布了一个我希望更清楚的问题:stackoverflow.com/questions/55345453/…
猜你喜欢
  • 1970-01-01
  • 2012-06-06
  • 2023-03-21
  • 1970-01-01
  • 2012-09-30
  • 2015-04-27
  • 1970-01-01
  • 2014-11-18
相关资源
最近更新 更多