以下代码应该创建频率分布 (nltk.FreqDist) 的新(修改)版本。两个变量应该是相同的长度。
创建 WebText 的单个实例时,它可以正常工作。但是当创建多个 WebText 实例时,新变量似乎被所有对象共享。
例如:
import nltk
from operator import itemgetter
class WebText:
freq_dist_weighted = {}
def __init__(self, text):
tokens = nltk.wordpunct_tokenize(text) #tokenize
word_count = len(tokens)
freq_dist = nltk.FreqDist(tokens)
for word,frequency in freq_dist.iteritems():
self.freq_dist_weighted[word] = frequency/word_count*frequency
print len(freq_dist), len(self.freq_dist_weighted)
text1 = WebText("this is a test")
text2 = WebText("this is another test")
text3 = WebText("a final sentence")
结果是
4 4
4 5
3 7
这是不正确的。由于我只是转置和修改值,因此每列中应该有相同的数字。如果我在循环之前重置 freq_dist_weighted ,它可以正常工作:
import nltk
from operator import itemgetter
class WebText:
freq_dist_weighted = {}
def __init__(self, text):
tokens = nltk.wordpunct_tokenize(text) #tokenize
word_count = len(tokens)
freq_dist = nltk.FreqDist(tokens)
self.freq_dist_weighted = {}
for word,frequency in freq_dist.iteritems():
self.freq_dist_weighted[word] = frequency/word_count*frequency
print len(freq_dist), len(self.freq_dist_weighted)
text1 = WebText("this is a test")
text2 = WebText("this is another test")
text3 = WebText("a final sentence")
结果(正确):
4 4
4 4
3 3
这对我来说没有意义。
我不明白为什么我必须重置它,因为它在对象中是孤立的。难道我做错了什么?