我试图找出一种方法来计算文档中特定术语的单词接近度以及平均接近度(按单词)。我知道关于 SO 有类似的问题,但没有什么能给我我需要的答案,甚至没有给我指出有用的地方。假设我有以下文字:
song <- "Far over the misty mountains cold To dungeons deep and caverns old We
must away ere break of day To seek the pale enchanted gold. The dwarves of
yore made mighty spells, While hammers fell like ringing bells In places deep,
where dark things sleep, In hollow halls beneath the fells. For ancient king
and elvish lord There many a gleaming golden hoard They shaped and wrought,
and light they caught To hide in gems on hilt of sword. On silver necklaces
they strung The flowering stars, on crowns they hung The dragon-fire, in
twisted wire They meshed the light of moon and sun. Far over the misty
mountains cold To dungeons deep and caverns old We must away, ere break of
day, To claim our long-forgotten gold. Goblets they carved there for
themselves And harps of gold; where no man delves There lay they long, and
many a song Was sung unheard by men or elves. The pines were roaring on the
height, The winds were moaning in the night. The fire was red, it flaming
spread; The trees like torches blazed with light. The bells were ringing in
the dale And men they looked up with faces pale; The dragon’s ire more fierce
than fire Laid low their towers and houses frail. The mountain smoked beneath
the moon; The dwarves they heard the tramp of doom. They fled their hall to
dying fall Beneath his feet, beneath the moon. Far over the misty mountains
grim To dungeons deep and caverns dim We must away, ere break of day,
To win our harps and gold from him!"
我希望能够看到每次出现在“火”(也可互换)单词两侧(左侧 15 和右侧 15)的 15 个(我希望这个数字是可互换的)单词内出现的单词出现。我想查看每个“火”实例的每个单词及其在这 15 个单词跨度中出现的次数。因此,例如,“火”被使用了 3 次。在这 3 次中,“光”一词在两侧各 15 个字以内出现两次。我想要一个显示单词的表格,它在指定的 15 附近出现的次数、最大距离(在本例中为 12)、最小距离(为 7)和平均距离(其中是 9.5)。
我想我需要几个步骤和包来完成这项工作。我的第一个想法是使用 quanteda 的“kwic”功能,因为它允许您围绕特定术语选择一个“窗口”。然后,基于 kwic 结果的术语频率计数并不难(去除了频率的停用词,但没有去除单词邻近度度量)。我真正的问题是找到与焦点术语的最大、最小和平均距离,然后将结果放入一个漂亮的整洁表中,这些术语按频率降序排列,列给我频率计数、最大距离、最小距离和平均距离。
这是我到目前为止所拥有的:
library(quanteda)
library(tm)
mysong <- char_tolower(song)
toks <- tokens(mysong, remove_hyphens = TRUE, remove_punct = TRUE,
remove_numbers = TRUE, remove_symbols = TRUE)
mykwic <- kwic(toks, "fire", window = 15, valuetype ="fixed")
thekwic <- as.character(mykwic)
thekwic <- removePunctuation(thekwic)
thekwic <- removeNumbers(thekwic)
thekwic <- removeWords(thekwic, stopwords("en"))
kwicFreq <- termFreq(thekwic)
任何帮助深表感谢。