我想从一组短文本中找到的字典中学习术语的位置。问题出在以下代码的最后一行,大致基于 From 的字符串列表,确定哪些是人名,哪些不是
library(tm)
pkd.names.quotes <- c(
"Mr. Rick Deckard",
"Do Androids Dream of Electric Sheep",
"Roy Batty",
"How much is an electric ostrich?",
"My schedule for today lists a six-hour self-accusatory depression.",
"Upon him the contempt of three planets descended.",
"J.F. Sebastian",
"Harry Bryant",
"goat class",
"Holden, Dave",
"Leon Kowalski",
"Dr. Eldon Tyrell"
)
firstnames <- c("Sebastian", "Dave", "Roy",
"Harry", "Dave", "Leon",
"Tyrell")
dict <- sort(unique(tolower(firstnames)))
corp <- VCorpus(VectorSource(pkd.names.quotes))
#strange but Corpus() gives wrong segment numbers for the matches.
tdm <-
TermDocumentMatrix(corp, control = list(tolower = TRUE, dictionary = dict))
inspect(corp)
inspect(tdm)
View(as.matrix(tdm))
data.frame(
Name = rownames(tdm)[tdm$i],
Segment = colnames(tdm)[tdm$j],
Content = pkd.names.quotes[tdm$j],
Postion = regexpr(
pattern = rownames(tdm)[tdm$i],
text = tolower(pkd.names.quotes[tdm$j])
)
)
输出带有警告,只有第一行正确。
Name Segment Content Postion
1 roy 3 Roy Batty 1
2 sebastian 7 J.F. Sebastian -1
3 harry 8 Harry Bryant -1
4 dave 10 Holden, Dave -1
5 leon 11 Leon Kowalski -1
6 tyrell 12 Dr. Eldon Tyrell -1
Warning message:
In regexpr(pattern = rownames(tdm)[tdm$i], text = tolower(pkd.names.quotes[tdm$j])) :
argument 'pattern' has length > 1 and only the first element will be used
我知道模式=粘贴(矢量,折叠="|")的解决方案但我的向量可能很长(所有流行名称)。
是否有此命令的简单矢量化版本或每行接受新模式参数的解决方案?
您可以使用mapply
对regexpr
进行矢量化:
mapply
是sapply
的多变量版本。mapply
将FUN应用于每个元素的第一个元素...参数、第二个元素、第三个元素,依此类推。
用
data.frame(
Name = rownames(tdm)[tdm$i],
Segment = colnames(tdm)[tdm$j],
Content = pkd.names.quotes[tdm$j],
Postion = mapply(regexpr, rownames(tdm)[tdm$i], tolower(pkd.names.quotes[tdm$j]), fixed=TRUE)
)
结果:
Name Segment Content Postion
roy roy 3 Roy Batty 1
sebastian sebastian 7 J.F. Sebastian 6
harry harry 8 Harry Bryant 1
dave dave 10 Holden, Dave 9
leon leon 11 Leon Kowalski 1
tyrell tyrell 12 Dr. Eldon Tyrell 11
或者,使用纵梁str_locate
:
在字符串和图案上矢量化
它返回:
对于
str_locate
,一个整数矩阵。第一列给出匹配的开始位置,第二列给出结束位置。
用
str_locate(tolower(pkd.names.quotes[tdm$j]), fixed(rownames(tdm)[tdm$i]))[,1]
请注意,如果您需要将字符串与固定字符串(即非正则表达式模式)匹配,则使用fixed()
。否则,删除fixed()
并fixed=TRUE
.