繁体   English   中英

函数python调用后没有返回内存

[英]Memory not being returned after function python call

我有一个函数可以通过构建图表来解析句子。 但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。

在函数中,您将rules设置为grammar元素; 然后rules引用该元素,即列表。 然后使用heappushrules添加到rules ,其中(因为列表是可变的)意味着grammar通过该列表保持推送的值。 如果您不希望发生这种情况,请在translate开始时为语法分配rulesdeepcopy copy时使用copy 请注意,即使将列表复制到rules ,每次检索缺失键的元素时,语法都会记录一个空列表。

运行该函数后尝试运行gc.collect

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM