如何创建二元矩阵?
how to create the bigram matrix?
我想做一个二元模型的矩阵。我该怎么做?请问有什么符合我的代码的建议吗?
import nltk
from collections import Counter
import codecs
with codecs.open("Pezeshki339.txt",'r','utf8') as file:
for line in file:
token=line.split()
spl = 80*len(token)/100
train = token[:int(spl)]
test = token[int(spl):]
print(len(test))
print(len(train))
cn=Counter(train)
known_words=([word for word,v in cn.items() if v>1])# removes the rare words and puts them in a list
bigram=nltk.bigrams(known_words)
frequency=nltk.FreqDist(bigram)
for f in frequency:
print(f,frequency[f])
我需要这样的东西:
w1 w2 w3 ....wn
w1 n(w1w1) n(w1w2) n(w1w3) n(w1wn)
w2 n(w2w1) n(w2w1) n(w2w3) n(w2wn)
w3 .
.
.
.
wn
所有行和列都相同。
由于您需要 "matrix" 个单词,因此您将使用类似字典的 class。你想要一本包含双字母组中所有第一个单词的字典。要制作一个二维矩阵,它将是一个字典的字典:每个值都是另一个字典,其键是双字母组的第二个词,值是您正在跟踪的任何内容(可能是出现次数)。
在 NLTK 中,您可以使用 ConditionalFreqDist()
:
快速完成
mybigrams = nltk.ConditionalFreqDist(nltk.bigrams(brown.words()))
但我建议您逐步构建二元语法 table。你会更好地理解它,你需要先了解它才能使用它。
我想做一个二元模型的矩阵。我该怎么做?请问有什么符合我的代码的建议吗?
import nltk
from collections import Counter
import codecs
with codecs.open("Pezeshki339.txt",'r','utf8') as file:
for line in file:
token=line.split()
spl = 80*len(token)/100
train = token[:int(spl)]
test = token[int(spl):]
print(len(test))
print(len(train))
cn=Counter(train)
known_words=([word for word,v in cn.items() if v>1])# removes the rare words and puts them in a list
bigram=nltk.bigrams(known_words)
frequency=nltk.FreqDist(bigram)
for f in frequency:
print(f,frequency[f])
我需要这样的东西:
w1 w2 w3 ....wn
w1 n(w1w1) n(w1w2) n(w1w3) n(w1wn)
w2 n(w2w1) n(w2w1) n(w2w3) n(w2wn)
w3 .
.
.
.
wn
所有行和列都相同。
由于您需要 "matrix" 个单词,因此您将使用类似字典的 class。你想要一本包含双字母组中所有第一个单词的字典。要制作一个二维矩阵,它将是一个字典的字典:每个值都是另一个字典,其键是双字母组的第二个词,值是您正在跟踪的任何内容(可能是出现次数)。
在 NLTK 中,您可以使用 ConditionalFreqDist()
:
mybigrams = nltk.ConditionalFreqDist(nltk.bigrams(brown.words()))
但我建议您逐步构建二元语法 table。你会更好地理解它,你需要先了解它才能使用它。