我该如何解决这个问题?
# E.g. word_count("I am that I am") gets back a dictionary like:
# {'i': 2, 'am': 2, 'that': 1}
# Lowercase the string to make it easier.
# Using .split() on the sentence will give you a list of words.
# In a for loop of that list, you'll have a word that you can
# check for inclusion in the dict (with "if word in dict"-style syntax).
# Or add it to the dict with something like word_dict[word] = 1.
def word_count(string):
word_list = string.split()
word_dict = {}
for word in word_list:
if word in word_dict:
word_dict.update(word:word_dict(word)+1)
else:
word_dict[word]=1
return word_dict
免责声明:Python 新手
最佳答案
要更新字典中的键,只需使用 [...]
订阅语法分配给该键即可:
word_dict[word] = word_dict[word] + 1
甚至
word_dict[word] += 1
您的尝试不是有效的语法,原因有两个:
word_dict.update()
是一个方法调用,(...)
调用语法中的所有内容都必须是有效的表达式。key: value
不是独立的表达式,仅在{key: value}
字典显示中有效。word_dict.update()
接受字典对象或(key, value)
对序列。word_dict(word)
会尝试调用字典,而不是尝试检索关键字word
的值。
使用 word_dict.update()
只更新一个键有点过大,因为它需要创建另一个字典或序列。以下任一方法都可以:
word_dict.update({word: word_dict[word] + 1})
或
word_dict.update([(word, word_dict[word] + 1)])
请注意,Python 标准库提供了更好的单词计数解决方案:collections.Counter()
class :
from collections import Counter
def word_count(string):
return Counter(string.split())
Counter()
是 dict
的子类。
关于python - 语法错误 :update for dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37506824/