【问题标题】:Python: dictionaries and word counting [duplicate]Python:字典和字数统计
【发布时间】:2016-04-11 23:10:04
【问题描述】:

我需要创建一个函数来读取一个字符串并返回一个字典,其中键是字符串中的单词,值是它们出现的次数。

这是我尝试过的:

    def countWords(arg):
        dic = {}
        for i in agr:
            if i in dic:
                dic[i] += 1
            else:
                dic[i] = 1
        return dic

只计算一个字母出现的次数。

我想先将每个单词分成列表的不同位置,但我不知道怎么做,甚至不知道这是否是正确的方法..

我该怎么办?

【问题讨论】:

标签: python dictionary


【解决方案1】:

collections.Counter。这通常被认为是此类问题的最佳解决方案。

from collections import Counter


def countWords(s):
    return Counter(s.split())

如果您不想使用集合模块,可以使用try...except 块。

def countWords(s):
    d = {}
    for word in s.split():
        try:
            d[word] += 1
        except KeyError:
            d[word] = 1
    return d

另一种选择是使用可选的默认参数dict.get()

def countWords(s):
    d = {}
    for word in s.split():
        d[word] = d.get(word, 0) + 1
    return d

如您所见,有许多不同的方法可以完成这项任务。

【讨论】:

  • 这个建议不适合 OP 的要求,IMO。他不是在问:“我如何计算一个句子或字符串中单词的频率”。
  • @nbro 当我添加第二个选项时,伯尼的答案还没有出现在我面前。当我看到他有更早的时间戳时,我删除了那部分答案。我最初的建议是最好的方法来解决这个任务。事实上,这个任务是我见过的最常见的 collections.Counter 用例。
【解决方案2】:

这是默认字典的完美案例:https://docs.python.org/2/library/collections.html#collections.defaultdict

import collections as co

def countWords(arg):
    dd = co.defaultdict(int) # since we want counts we use int
    for i in arg.split():    # split on whitespace
        dd[i] += 1           # when a new key is encountered the default value is entered
    return dd

【讨论】:

  • 谢谢!我发现我不需要导入。我设法只使用 split
  • 不客气。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 1970-01-01
  • 2017-11-13
  • 1970-01-01
  • 2023-01-04
  • 2016-12-31
  • 1970-01-01
相关资源
最近更新 更多