初始化字典,循环列表,添加单词并增加字典计数器

-1 投票
2 回答
3031 浏览
提问于 2025-04-18 13:50

我加了一个例子,希望能让这个问题更清楚。我想做的事情是:把句子中不在单词字典里的词放到一个列表里,然后把这些词加到一个叫做 'new_words_dict' 的字典里。每个词只加一次,不允许重复,并且要有一个计数器来记录这个词出现了多少次。比如说,'happy' 这个词在字典里只出现一次,但计数器的值是 2。

我能创建列表并把词加到字典里,但我没有正确地增加字典里的值。

words = {'abandon':-2,'abandoned':-2,'abandons':-2,'abducted':-2,'abduction':-2,
'abductions':-2,'abhor': -3}
sentence = {'abandon', 'abandoned', 'abhorrent', 'hello', 'smart', 'hello', 'die',
'happy', 'sad', 'up', 'down', 'happy', 'smart','cool', 'clean', 'mean'}         

new_words_list = []                  #Empty list
new_words_dict = {}                  #Empty dict 

for word in sentence:
if word not in words:    
        new_words_list.append(word)  
print new_words_list        

for word in new_words_list:
    if word not in new_words_dict:
        new_words_dict[word] = {}
        new_words_dict[word] =1
else:
    if word in new_words_dict:
        new_words_dict[word] +=1              
print new_words_dict

这段代码打印出了 new_words_dict,但计数器的值没有正确增加。

2 个回答

0

我同意msw的看法,你的代码有点复杂,其实可以简化。不过,既然你想坚持用这段代码并从中学习,那我就给你加一些注释和修改建议:

# dictionary with weird values, but we're only counting keys anyway
words = {'abandon':-2,'abandoned':-2,'abandons':-2,'abducted':-2,'abduction':-2,
'abductions':-2,'abhor': -3}
# this is a list, not a dictionary!
sentence = ['abandon', 'abandoned', 'abhorrent', 'hello', 'smart', 'hello', 'die',
'happy', 'sad', 'up', 'down', 'happy', 'smart','cool', 'clean', 'mean']

# empty list to save words in
new_words_list = []
# empty dict to save words and counts in
new_words_dict = {}

# first loop finds new words and saves them in new_words_list
for word in sentence:
  if word not in words:    
    new_words_list.append(word)  
print new_words_list        

# second loop counts new words
for word in new_words_list:

  # if the word is not in the dictionary yet, add it as key with another
  # dictionary as value (which doesn't make sense). Then replace this empty
  # dictionary with a simple integer (1).
  if word not in new_words_dict:
    new_words_dict[word] = {}
    new_words_dict[word] = 1

  # this should be elif, I assume. Then it would increment the counter of the
  # word in new_words_dict by 1.
  elif word in new_words_dict:
    new_words_dict[word] += 1              
print new_words_dict

请注意,在第二个循环中,new_words_dict[word] = {} 这行代码其实没什么意义,因为你需要的是一个计数器,而不是一个字典。

顺便说一下,我觉得你的计数器没有问题。这可能是因为我修正了你elseelif语句的缩进(我不确定你在这里没有缩进,还是在你原来的代码中也没有缩进?)。

1

你这样做有点复杂,而且让人困惑。其实可以用 collections.Counter 来帮你完成大部分工作:

import collections

words = {'abandon':-2,'abandoned':-2,'abandons':-2,'abducted':-2,'abduction':-2,
'abductions':-2,'abhor': -3}
# throw away the values in the dictionary because they aren't being used
words = words.keys()  

# this is a list [] not a dictionary ()
sentence = ['abandon', 'abandoned', 'abhorrent', 'hello', 'smart', 'hello', 
    'die', 'happy', 'sad', 'up', 'down', 'happy', 'smart','cool',
    'clean', 'mean'] 


counts = collections.Counter([word for word in sentence if word not in words])

print counts 
Counter({'hello': 2, 'smart': 2, 'happy': 2, 'down': 1, 'die': 1, 'up': 1, 
'sad':1, 'abhorrent': 1, 'clean': 1, 'mean': 1, 'cool': 1})

不过,可能这并不是你真正想要的,因为你的代码有点问题。根据我理解的情况,它确实能做到你问题中提到的内容。

撰写回答