gpt4 book ai didi

r - 如何计算 R 中的文本行数?

转载 作者:行者123 更新时间:2023-12-01 08:07:14 25 4
gpt4 key购买 nike

我想使用 R 计算文本中不同发言者所说的行数(它是议会发言记录的抄本)。基本文本如下所示:

MR. JOHN: This activity has been going on in Tororo and I took it up with the office of the DPC. He told me that he was not aware of it.
MS. SMITH: Yes, I am aware of that.
MR. LEHMAN: Therefore, I am seeking your guidance, Madam Speaker, and requesting that you re-assign the duty.
MR. JOHN: Thank you

在文档中,每位发言者都有一个以 MR/MS 开头且始终大写的标识符。我想创建一个数据集,该数据集计算每个发言者在文档中每次发言时所说的行数,这样上述文本将导致:

MR. JOHN: 2
MS. SMITH: 1
MR. LEHMAN: 2
MR. JOHN: 1

感谢使用 R 的指针!

最佳答案

您可以使用模式 : 来分割字符串,然后使用 table:

table(sapply(strsplit(x, ":"), "[[", 1))
# MR. JOHN MR. LEHMAN MS. SMITH
# 2 1 1

strsplit - splits strings at : and results in a list
sapply with [[ - selects the first part element of the list
table - gets the frequency

编辑:遵循 OP 的评论。您可以将成绩单保存在 文本文件 中,然后使用 readLines 读取 R 中的文本。

tt <- readLines("./tmp.txt")

现在,我们必须找到一种模式来过滤此文本,以筛选出带有发言者姓名的那些行。根据我在您链接的成绩单中看到的内容,我可以想到两种方法。

  • 检查 :,然后 lookbehind : 看它是否是 A-Z[:punct:] (也就是说,如果出现在 : 之前的字符是任何大写字母或任何标点符号 - 这是因为其中一些具有 ):) 之前。

你可以使用 strsplit 后跟 sapply (如下图)

使用 strsplit:

# filter tt by pattern
tt.f <- tt[grepl("(?<=[A-Z[:punct:]]):", tt, perl = TRUE)]
# Now you should only have the required lines, use the command above:

out <- table(sapply(strsplit(tt.f, ":"), "[[", 1))

还有其他可能的方法(例如,使用 gsub :)或替代模式。但这应该让您对这种方法有所了解。如果模式应该不同,那么您应该更改它以捕获所有必需的行。

当然,这里假设没有其他行,例如,像这样:

"Mr. Chariman, whatever (bla bla): It is not a problem"

因为我们的模式将为 ): 提供 TRUE。如果文本中出现这种情况,您将不得不找到更好的模式。

关于r - 如何计算 R 中的文本行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15326689/

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