我写了a package a little while ago to take care of WhatsApp data。我将使用source code 的重要部分和示例数据向您展示如何自己做到这一点。首先,让我们获取一些示例数据:
chat_raw <- scan(text = "
12/07/2017, 22:35 - Messages to this group are now secured with end-to-end encryption. Tap for more info.
12/07/2017, 22:35 - You created group 'Tes'
12/07/2017, 22:35 - Johannes Gruber: <Media omitted>
12/07/2017, 22:35 - Johannes Gruber: Fruit bread with cheddar <U+263A><U+0001F44C><U+0001F3FB>
13/07/2017, 09:12 - Test: It's fun doing text analysis with R
isn't it?
13/07/2017, 09:16 - Johannes Gruber: Haha it sure is <U+0001F605>
28/09/2018, 13:27 - Johannes Gruber: Did you know there is an incredible number of emojis in WhatsApp? Check it out:
", what = character(), sep = "\n")
这给我们留下了一个对象,就像我们使用readLines() 得到的一样:每一行文本都是字符向量的一个元素。现在我们可以使用正则表达式提取时间戳:
time <- stringi::stri_extract_first_regex(
str = chat_raw,
pattern = "^\\d{2}/\\d{2}/\\d{4}, \\d{2}:\\d{2}"
)
\\d{2} 是一个有两个字符的数字,\d{4} 是一个有四个字符的数字。您必须更改数字之间的字符才能获得正确的日期格式。我在这里使用stringi 以提高速度,但很多人发现stringr 更方便,并且功能的工作方式几乎相同。现在time 向量看起来像这样:
time
#> [1] "12/07/2017, 22:35" "12/07/2017, 22:35" "12/07/2017, 22:35"
#> [4] "12/07/2017, 22:35" "13/07/2017, 09:12" NA
#> [7] "13/07/2017, 09:16" "28/09/2018, 13:27"
我们从每一行中获取了一个时间,但没有时间戳的那一行。我们可以在没有时间戳的情况下遍历所有行并将其中的字符添加到之前的行:
for (l in which(is.na(time))) {
chat_raw[l - 1] <- stringi::stri_paste(chat_raw[l - 1], chat_raw[l],
sep = " ")
}
which(is.na(time)) 在这种情况下将仅返回 6,因为这是时间为 NA 的唯一行。所以你可以把chat_raw[l - 1]读成chat_raw[5],即chat_raw的第五行。 stringi::stri_paste 与 paste() 相同,因此将第 6 行添加到第 5 行。您可以根据需要选择不同的分隔符。我选择"\n" 在我的包中标记换行符。现在chat_raw 和time 向量仍然有这个对我们现在无用的附加元素。我们可以删除它:
chat_raw <- chat_raw[!is.na(time)]
time <- time[!is.na(time)]
为了把它变成一个好的格式,让我们用它制作一个 data.frame:
tibble::tibble(
time = time,
text = chat_raw
)
#> # A tibble: 7 x 2
#> time text
#> <chr> <chr>
#> 1 12/07/2017, 22~ 12/07/2017, 22:35 - Messages to this group are now secur~
#> 2 12/07/2017, 22~ 12/07/2017, 22:35 - You created group 'Tes'
#> 3 12/07/2017, 22~ 12/07/2017, 22:35 - Johannes Gruber: <Media omitted>
#> 4 12/07/2017, 22~ 12/07/2017, 22:35 - Johannes Gruber: Fruit bread with ch~
#> 5 13/07/2017, 09~ 13/07/2017, 09:12 - Test: It's fun doing text analysis w~
#> 6 13/07/2017, 09~ 13/07/2017, 09:16 - Johannes Gruber: Haha it sure is <U+~
#> 7 28/09/2018, 13~ 28/09/2018, 13:27 - Johannes Gruber: Did you know there ~
给你,漂亮干净的输出:)
如果您想对您的 whatsapp 数据做更多事情,请通过demo of my package 工作。我没有在 CRAN 上发布它,因为我认为到目前为止贡献有点小,但如果你能想到很酷的功能,我可以添加它们,也许随着时间的推移它会成为一个合法的包。