繁体   English   中英

几个从文本文件中查找和替换

[英]Several find and replace from text file

我有一个文本文件想要将其转换为数据框。 文本很乱,需要清理,删除几个重复的句子,替换新行(单词中的通配符是“^p”到制表符或逗号...

例如我的文本文件是这样的:

-The data 1 is taken on Aug, 2009 at UBC
and is significant with p value <0.01

-The data 2 is taken on Sep, 2012 at SFU
and is  not significant with p value > 0.06

我怎样才能进行多次查找和替换。 我使用了这段代码:

tx = readLines("My_text.txt")
tx2 = gsub(pattern = "is taken on", replace = " ", x = tx)
tx3 = gsub(pattern = "at", replace = " ", x = tx2)
writeLines(tx3, con="tx3.txt")

但我不知道如何将“at”替换为制表符 (^t),或者如何将 (^p) 替换为,或者例如 space^p (^p) 替换为,

使用正则表达式来考虑单词边界\\b

为了避免多个gsub()我们可以使用替换矩阵rmx

rmx <- matrix(c("\\sis taken on\\s\\b", " ",  
                "\\b\\sat\\s", "\t"          #  replace with tab
                ), 2)        
#      [         ,1]                   [,2]         
# [1,] "\\sis taken on\\s\\b" "\\b\\sat\\s"
# [2,] " "                    "\t"   

现在我们可以使用apply()逐列为gsub()提供rmx 要对tx进行永久性更改,我们可以使用<<-运算符。 为了避免向控制台发送垃圾邮件,我们可以用一个invisible()包裹整个东西。

tx <- readLines("My_text.txt")
invisible(
  apply(rmx, MARGIN=2, function(x) tx <<- gsub(x[1], x[2], tx))
  )

为了获得连续的文本而不是段落(我假设你的意思是^p -replacement),我们可以简单地paste()结果,用, collapse 应该使用tx != ""过滤掉空字符串。

tx <- paste(tx[tx != ""], collapse=", ")

现在writeLines()

writeLines(tx, con="tx4.txt")

结果

- 2009 年 8 月 1 日 UBC 的数据,且 p 值 <0.01 显着, - 2012 年 9 月 2 日 SFU 的数据,且 p 值 > 0.06 不显着

附录

我们也可以通过双重转义替换 R 中的特殊字符——阅读这篇文章

gsub("\\$", "\t", "today$is$monday")
# [1] "today\tis\tmonday"

使用 jay.sf 提供的正则表达式,您可以使用stringr package 中的str_replace_all来处理命名向量。

library(stringr)

new_tx <- str_replace_all(tx,
                          c("\\sis taken on\\s" = " ",
                            "\\b\\sat\\s" = "\t",
                            "\\b\\sp\\b" = ","))

cat(new_tx)

结果

-The data 1 Aug, 2009    UBC
and is significant with, value <0.01

-The data 2 Sep, 2012    SFU
and is  not significant with, value > 0.06

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM