我已经添加了一个例子,希望能让这个更加清晰。我尝试执行以下操作:将单词dict中不包含单词的单词添加到列表中,然后将这些单词添加到字典“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,但值计数器不会正确递增。
答案 0 :(得分: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})
这可能不是您实际想要的,因为您的代码已经破坏了。据我所知,它确实可以满足您的问题。
答案 1 :(得分: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] = {}
没有任何意义,因为您需要计数器而不是字典。
顺便说一下,我在这里看不到柜台的任何问题。这可能是因为我更正了else
/ elif
声明的缩进(如果您在此处或原始代码中没有缩进,我不会起诉)。