gpt4 book ai didi

r - 如何将 2 行或更多行文本合并为 1 行,条件是 R

转载 作者:行者123 更新时间:2023-12-04 04:05:52 24 4
gpt4 key购买 nike

我想将 Thunderbird Mozilla 的 Sent 文件读入 R。有时必须将 2 行或更多行放在 1 行中。这些行以 ',' 逗号结尾例如:

From: Frans  <frans@zeenit.nl>
Subject: volledig overzicht beschikbaar
To: aldjan@gmail.com, clen@zeenit.nl, pinge1@zeenit.nl,
griepje@zeenit.nl, Jowialj@live.com, pelicaan@hotmail.com,
pico11@zeenit.nl
Date: Mon, 21 Mar 2016 14:17:09 +0100

合并后:

From: Frans  <frans@zeenit.nl>
Subject: volledig overzicht beschikbaar
To: aldjan@gmail.com, clen@zeenit.nl, pinge1@zeenit.nl, griepje@zeenit.nl, Jowialj@live.com, pelicaan@hotmail.com, pico11@zeenit.nl
Message-ID: <56EFF455.5000006@zeenit.nl>
Date: Mon, 21 Mar 2016 14:17:09 +0100

最佳答案

我不会只依赖逗号。使用 grep 您可以识别带有 To: 标记的行并粘贴所有行直到带有以下标记的行 Message-ID:/Date:: >.

cleanHeader <- function(x) {
line.to <- grep("^To", header)
line.next <- grep("^Date|^Mess", header)[1]
new.to <- paste(header[line.to:(line.next - 1)], collapse="")
c(header[1:(line.to - 1)], new.to, header[line.next:length(header)])
}

结果

cleanHeader(header1)  
[1] "From: Frans <frans@zeenit.nl>"
[2] "Subject: volledig overzicht beschikbaar"
[3] "To: aldjan@gmail.com, clen@zeenit.nl, pinge1@zeenit.nl, griepje@zeenit.nl,
Jowialj@live.com, pelicaan@hotmail.com, pico11@zeenit.nl"
[4] "Date: Mon, 21 Mar 2016 14:17:09 +0100"

cleanHeader(header2)
[1] "From: Frans <frans@zeenit.nl>"
[2] "Subject: volledig overzicht beschikbaar"
[3] "To: aldjan@gmail.com, clen@zeenit.nl, pinge1@zeenit.nl, griepje@zeenit.nl,
Jowialj@live.com, pelicaan@hotmail.com, pico11@zeenit.nl"
[4] "Message-ID: <56EFF455.5000006@zeenit.nl>"
[5] "Date: Mon, 21 Mar 2016 14:17:09 +0100"

数据:

tmp <- tempfile()

cat("From: Frans <frans@zeenit.nl>
Subject: volledig overzicht beschikbaar
To: aldjan@gmail.com, clen@zeenit.nl, pinge1@zeenit.nl,
griepje@zeenit.nl, Jowialj@live.com, pelicaan@hotmail.com,
pico11@zeenit.nl
Date: Mon, 21 Mar 2016 14:17:09 +0100", file=tmp, sep="\n")

header1 <- readLines(tmp)

cat("From: Frans <frans@zeenit.nl>
Subject: volledig overzicht beschikbaar
To: aldjan@gmail.com, clen@zeenit.nl, pinge1@zeenit.nl, griepje@zeenit.nl, Jowialj@live.com, pelicaan@hotmail.com, pico11@zeenit.nl
Message-ID: <56EFF455.5000006@zeenit.nl>
Date: Mon, 21 Mar 2016 14:17:09 +0100", file=tmp, sep="\n")

header2 <- readLines(tmp)

关于r - 如何将 2 行或更多行文本合并为 1 行,条件是 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62530984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com