有人如何在字符向量中找到频繁的相邻单词对?以原油数据集为例,一些常见的对是“原油”、“石油市场”和“百万桶”。
下面的小示例的代码尝试识别频繁项,然后使用积极的前瞻断言,计算这些频繁项后面紧跟一个频繁项的次数。但这次尝试失败并烧毁了。
关于如何创建在第一列(“Pairs”)中显示常见对和在第二列(“Count”)中显示它们在文本中出现的次数的任何指导,将不胜感激。
library(qdap)
library(tm)
# from the crude data set, create a text file from the first three documents, then clean it
text <- c(crude[[1]][1], crude[[2]][1], crude[[3]][1])
text <- tolower(text)
text <- tm::removeNumbers(text)
text <- str_replace_all(text, " ", "") # replace double spaces with single space
text <- str_replace_all(text, pattern = "[[:punct:]]", " ")
text <- removeWords(text, stopwords(kind = "SMART"))
# pick the top 10 individual words by frequency, since they will likely form the most common pairs
freq.terms <- head(freq_terms(text.var = text), 10)
# create a pattern from the top words for the regex expression below
freq.terms.pat <- str_c(freq.terms$WORD, collapse = "|")
# match frequent terms that are followed by a frequent term
library(stringr)
pairs <- str_extract_all(string = text, pattern = "freq.terms.pat(?= freq.terms.pat)")
这就是努力失败的地方。
不了解 Java 或 Python,这些对Java 计算单词对 没有帮助Python 计算单词对,但它们可能对其他人有用。
谢谢你。