对于使用ngram的下一个单词预测,我需要找到给定n-1个前单词的所有ngram(及其频率)。
在dfm中,我看不到任何方法,因此开始在texstat_frequency(data.frame)上手动实现它。
在碰到一些this page中文档不清楚的方法之后,想知道是否有一种方法,只是我看不到它(也许是其中列出的但没有以某种方式描述的“ [”方法之一)我在那儿明白),所以这个问题。
(由于偏见,在成千上万的字符串上运行它们可能太慢/太重,这有可能导致错误地排除了我通常喜欢的正则表达式)
txt <- c("a b 1 2 3 a b 2 3 4 a b 3 4 5")
fcm(tokens(txt, ngram = 2), "window", window = 1, ordered = T)
Feature co-occurrence matrix of: 10 by 10 features.
10 x 10 sparse Matrix of class "fcm"
features
features a_b b_1 1_2 2_3 3_a b_2 3_4 4_a b_3 4_5
a_b 0 1 0 0 0 1 0 0 1 0
b_1 0 0 1 0 0 0 0 0 0 0
1_2 0 0 0 1 0 0 0 0 0 0
2_3 0 0 0 0 1 0 1 0 0 0
3_a 1 0 0 0 0 0 0 0 0 0
b_2 0 0 0 1 0 0 0 0 0 0
3_4 0 0 0 0 0 0 0 1 0 1
4_a 1 0 0 0 0 0 0 0 0 0
b_3 0 0 0 0 0 0 1 0 0 0
4_5 0 0 0 0 0 0 0 0 0 0
以上代码使用了从github 2018年8月20日安装的Quanteda,其中应包含此问题生成的this fix
packageVersion("quanteda")
[1] ‘1.3.5’
答案 0 :(得分:0)
包装提供者请提供示例代码(here),该示例代码说明了如何实现我要求的内容(对于文本不太大的内容)。我在这里重现该代码,并进行一些简化和注释,以使其尽可能容易理解
sample_code <- function() {
require(quanteda)
print(paste("based on","https://github.com/quanteda/quanteda/issues/1413#issuecomment-414795832"))
print("great package great support, thanks")
ngms <- tokens("a b 1 2 3 a b 2 3 4 a b 3 4 5", n = 2:5)
# get rid of tokens metadata not necessary for our UC
ngms_lst <- as.list(ngms)
ngms_unlst <- unlist(ngms_lst) # (named) character with _ sep. ngrams
# split in " "-separated pairs: "n-1 tokens", "nth token"
ngms_blank_sep <- stringi::stri_replace_last_fixed(ngms_unlst,"_", " ")
# list of character(2) ( (n-1)gram ,nth token )
tk2_lst <- tokens(ngms_blank_sep)
# --- end of tokens/ngrams pre-processing
# ordinary fcm
fcm_ord <- fcm(tk2_lst , ordered = TRUE)
fcm_ord[33:39, 1:6]
}
sample_code()
[1] "based on https://github.com/quanteda/quanteda/issues/1413#issuecomment-414795832"
[1] "great package great support, thanks"
Feature co-occurrence matrix of: 7 by 6 features.
7 x 6 sparse Matrix of class "fcm"
features
features a b 1 2 3 4
3_a_b_2 0 0 0 0 1 0
a_b_2_3 0 0 0 0 0 1
b_2_3_4 1 0 0 0 0 0
2_3_4_a 0 1 0 0 0 0
3_4_a_b 0 0 0 0 1 0
4_a_b_3 0 0 0 0 0 1
a_b_3_4 0 0 0 0 0 0