【问题标题】:word frequency program in pythonpython中的词频程序
【发布时间】:2011-03-08 17:18:10
【问题描述】:

假设我有一个名为 words 的单词列表,即 words = ["hello", "test", "string", "people", "hello", "hello"] 我想创建一个字典以便获取词频。

假设字典名为“counts”

counts = {}
for w in words:
    counts[w] = counts.get(w,0) + 1

我不明白的唯一部分是counts.get(w.0)。书上说,通常你会使用 counts[w] = counts[w] + 1 但是当你第一次遇到一个新单词时,它不会在 counts 中,所以它会返回一个运行时错误。这一切都很好,但 counts.get(w,0) 到底是做什么的?具体来说,(w,0) 符号是什么意思?

【问题讨论】:

    标签: python dictionary word-frequency


    【解决方案1】:

    如果您有字典,get() 是一种方法,其中 w 是一个变量,用于保存您正在查找的单词,0 是默认值。如果字典中不存在w,则get 返回0。

    【讨论】:

      【解决方案2】:

      FWIW,使用 Python 2.7 及更高版本您可能更喜欢使用 collections.Counter 进行操作,例如:

      In []: from collections import Counter
      In []: c= Counter(["hello", "test", "string", "people", "hello", "hello"])
      In []: c
      Out[]: Counter({'hello': 3, 'test': 1, 'people': 1, 'string': 1})
      

      【讨论】:

        【解决方案3】:

        如果键不存在,字典get() 方法允许将默认值作为第二个参数。所以如果w 在counts 中不存在,counts.get(w,0) 会给你0。

        【讨论】:

        • 值得一提的是,如果counts 中没有键w,那么counts.get(w) 将评估为None。而counts.get(w) + 1 行将等价于None + 1,并会抛出一个TypeError。
        【解决方案4】:

        字典上的get 方法返回存储在键中的值,或者可选的默认值,由可选的第二个参数指定。在您的情况下,您告诉它“如果该键尚未在字典中,则为先前的计数检索 0,然后向该值添加一个并将其放入字典中。”

        【讨论】:

          猜你喜欢
          • 2015-02-09
          • 1970-01-01
          • 2023-03-19
          • 1970-01-01
          • 1970-01-01
          • 2019-02-01
          • 1970-01-01
          • 2020-08-08
          • 1970-01-01
          相关资源
          最近更新 更多