python - 语法错误 :update for dictionary

标签 python string dictionary

我该如何解决这个问题?

# 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

enter image description here

免责声明: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/

相关文章:

python - 在矩阵图上绘图

python - 列表理解中的问题以获得计数

python - 如何针对每个特征图单独执行卷积

Python 的 Mechanize 无法识别 HTML 和 BeautifulSoup 所做的表单

regex - 根据文件名中的时间戳值复制文件

java - 用 + 连接创建的字符串是否存储在字符串池中?

python - 扩展 Dict 类的正确方法是什么?

python - 如何获取 `a` 和 `b` 字典的联合键以及 'a' 值?

Python 正则表达式没有按预期工作

c - 使用 getline 将字符串读取到指针数组中 (C)