这是我长期以来一直在绞尽脑汁的一个问题,所以任何帮助都会很棒。我有一个文件,其中包含以下格式的几行(单词,单词出现的时间,以及在给定实例中包含给定单词的文档的频率)。下面是输入文件的示例。
#inputfile
<word, time, frequency>
apple, 1, 3
banana, 1, 2
apple, 2, 1
banana, 2, 4
orange, 3, 1
我有下面的 Python 类,我用来创建二维字典来存储上述文件,使用作为键,频率作为值:
class Ddict(dict):
'''
2D dictionary class
'''
def __init__(self, default=None):
self.default = default
def __getitem__(self, key):
if not self.has_key(key):
self[key] = self.default()
return dict.__getitem__(self, key)
wordtime=Ddict(dict) # Store each inputfile entry with a <word,time> key
timeword=Ddict(dict) # Store each inputfile entry with a <time,word> key
# Loop over every line of the inputfile
for line in open('inputfile'):
word,time,count=line.split(',')
# If <word,time> already a key, increment count
try:
wordtime[word][time]+=count
# Otherwise, create the key
except KeyError:
wordtime[word][time]=count
# If <time,word> already a key, increment count
try:
timeword[time][word]+=count
# Otherwise, create the key
except KeyError:
timeword[time][word]=count
我的问题与在迭代此 2D 字典中的条目时计算某些事物有关。对于每个时间 't' 的每个单词 'w',计算:
- 在时间 't'内包含 单词 'w'的文档数。(一个)
- 在时间 't'内没有 单词 'w'的文档数。(二)
- 在时间 't'之外带有 单词 'w'的文档数。(C)
- 在时间 't'之外没有 单词 'w'的文档数。(d)
上面的每个项目代表每个单词和时间的卡方列联表的一个单元格。所有这些都可以在一个循环中计算,还是需要一次完成一个?
理想情况下,我希望输出如下所示,其中 a、b、c、d 是上面计算的所有项目:
print "%s, %s, %s, %s" %(a,b,c,d)
在上述输入文件的情况下,尝试在时间 '1' 查找单词 'apple' 的列联表的结果将是(3,2,1,6)
. 我将解释如何计算每个单元格:
- '3' 文档在时间'1' 内包含'apple'。
- 在时间“1”内有“2”个文档不包含“apple”。
- 在时间 '1' 之外有 '1' 个包含 'apple' 的文档。
- 在时间 '1' 之外有 6 个文档不包含单词 'apple' (1+4+1)。