gpt4 book ai didi

python - 函数 python 调用后未返回内存

转载 作者:行者123 更新时间:2023-11-28 18:52:40 25 4
gpt4 key购买 nike

我有一个函数可以通过构建图表来解析句子。但是 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 然后引用该元素,它是一个列表。然后,您使用 heappush 将项目添加到 rules,这(因为列表是可变的)意味着 grammar 保留通过该列表推送的值。如果您不想发生这种情况,请使用 copytranslate 开头的语法上分配 rulesdeepcopy 时。请注意,即使您将列表复制到 rules,每次您检索缺少键的元素时,语法都会记录一个空列表。

关于python - 函数 python 调用后未返回内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9856326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com