我有一个通过构建图表来解析句子的函数。但Python保留了在函数调用期间分配的任何内存。也就是说,我做了
best = translate(sentence, grammar)
不知何故,我的记忆力上升并保持不变。这是功能:
from string import join
from heapq import nsmallest, heappush
from collections import defaultdict
MAX_TRANSLATIONS=4 # or choose something else
def translate(f, g):
words = f.split()
chart = {}
for col in range(len(words)):
for row in reversed(range(0,col+1)):
# get rules for this subspan
rules = g[join(words[row:col+1], ' ')]
# ensure there's at least one rule on the diagonal
if not rules and row==col:
rules=[(0.0, join(words[row:col+1]))]
# pick up rules below & to the left
for k in range(row,col):
if (row,k) and (k+1,col) in chart:
for (w1, e1) in chart[row, k]:
for (w2, e2) in chart[k+1,col]:
heappush(rules, (w1+w2, e1+' '+e2))
# add all rules to chart
chart[row,col] = nsmallest(MAX_TRANSLATIONS, rules)
(w, best) = chart[0, len(words)-1][0]
return best
g = defaultdict(list)
g['cela'] = [(8.28, 'this'), (11.21, 'it'), (11.57, 'that'), (15.26, 'this ,')]
g['est'] = [(2.69, 'is'), (10.21, 'is ,'), (11.15, 'has'), (11.28, ', is')]
g['difficile'] = [(2.01, 'difficult'), (10.08, 'hard'), (10.19, 'difficult ,'), (10.57, 'a difficult')]
sentence = "cela est difficile"
best = translate(sentence, g)
我在OS X上使用Python 2.7。
答案 0 :(得分:1)
在函数中,您将rules
设置为grammar
的元素; rules
然后引用该元素,这是一个列表。然后,您使用rules
将项目添加到heappush
,其中(因为列表是可变的)意味着grammar
通过该列表保持推送的值。如果您不希望发生这种情况,请在rules
开头的语法上分配deepcopy
或translate
时使用copy
。请注意,即使将列表复制到rules
,每次检索缺失键的元素时,语法都会记录一个空列表。
答案 1 :(得分:0)
运行该功能后尝试运行gc.collect
。