我想計算已轉(zhuǎn)換為標記的文本文件中特定單詞前后三個單詞的頻率。from nltk.tokenize import sent_tokenizefrom nltk.tokenize import word_tokenizefrom nltk.util import ngramswith open('dracula.txt', 'r', encoding="ISO-8859-1") as textfile: text_data = textfile.read().replace('\n', ' ').lower()tokens = nltk.word_tokenize(text_data)text = nltk.Text(tokens)grams = nltk.ngrams(tokens, 4)freq = Counter(grams)freq.most_common(20)我不知道如何搜索字符串 'dracula' 作為過濾詞。我也試過:text.collocations(num=100)text.concordance('dracula')所需的輸出看起來像這樣的計數(shù):“dracula”之前的三個詞,排序計數(shù)(('and', 'he', 'saw', 'dracula'), 4),(('one', 'cannot', 'see', 'dracula'), 2)'dracula' 后面的三個詞,排序計數(shù)(('dracula', 'and', 'he', 'saw'), 4),(('dracula', 'one', 'cannot', 'see'), 2)中間包含 'dracula' 的三元組,排序計數(shù)(('count', 'dracula', 'saw'), 4),(('count', 'dracula', 'cannot'), 2)預先感謝您的任何幫助。
添加回答
舉報
0/150
提交
取消