我在此处获得帮助的功能上遇到了问题,我正在尝试理解并更正它。
这是函数(添加了一些注释/打印只是为了帮助我调试)
def accumulate_by_category(word_values, cat_sums, cats):
for word, value in word_values.items():
print word
for cat in cats[word]:
print cat
#cat_sums[cat] += value
cat_sums[cat].append(value)
print cat_sums
现在,word_values 应该看起来像这样:
{'a': 4, 'angry': 0, 'sad': 0, 'grateful': 0, 'happy': 0}
cat_sums 应该是这样的:
defaultdict(<type 'list'>, {'composed': [0], 'elated': [0], 'unsure': [0], 'hostile': [0], 'tired': [0], 'depressed': [0], 'guilty': [0], 'confused': [0], 'clearheaded': [0], 'anxious': [0], 'confident': [0], 'agreeable': [0], 'energetic': [0]})
猫应该是这样的:
defaultdict(<type 'list'>, {'depressed': ['sad'], 'elated': ['happy', 'grateful', 'a'], 'hostile': ['angry']})
基本上,该函数试图做的是获取 word_values 中的每个值,并将这些值最终添加到 cat_sums。这不是当前正在发生的事情——出于某种原因,没有任何值被附加。我很难弄清楚为什么 - 当我尝试 print cat 时,它显示为空白。但是 print word 给了我一个单词列表。理论上,for cat in cats[word] 应该会出现 cats 中的每个术语,但事实并非如此。
我做错了什么?
我最终只想将所有值添加到 cat_sums,以便我可以将其写入数据库。另外,我是否必须返回 cat_sums 的值才能执行此操作?
这是我写数据库的代码(catnums是提交给cat_sums的参数):
for key in catnums:
x = catnums[key]
for value in x:
cmd = "UPDATE resulttest SET value=\"" + str(value) + "\" WHERE category=\"" + key + "\"";
c.execute(cmd)
db.commit()
请您参考如下方法:
完全搞砸了! cats[word] 是什么意思? 在猫中:按键应该是“压抑”、“兴高采烈”、“敌对” 但在 word_values 中,它们是“愤怒”、“快乐”、“悲伤”、“感激”
我做了一些更改,希望这就是您想要的。
def accumulate_by_category(word_values, cat_sums, cats):
for word, value in word_values.items():
print word
for k, v in cats.items():
if word in v:
print k
if not cat_sums.has_key(k):
cat_sums[k] = 0
cat_sums[k] += value
print cat_sums
break
