【问题标题】:Turning a list into a frequency dictionary将列表变成频率字典
【发布时间】:2022-11-16 05:33:43
【问题描述】:

我目前正在尝试将列表变成频率字典。我正在读取一个文件,将文件分成一行中的每个单独的单词,并试图将每个单词转换成它自己的频率词典,以便找出它出现的次数。我想知道我将如何做到这一点。这就是我目前拥有的:

with open(file, 'r', encoding = 'utf-8') as fp:
    lines = fp.readlines()
    for row in lines:
        for word in row.split():
            print(word)

目前,我的程序在每一行输出一个新词。我该怎么做才能让每个单词都是自己的词典并且可以找到它们的频率?

【问题讨论】:

  • 顺便说一句,不要做lines = fp.readlines()。只是直接循环fp

标签: python


【解决方案1】:

Counter 类正是为这个任务而设计的。

from collections import Counter
with open(file, 'r', encoding='utf-8') as fp:
    counts = Counter(fp.read().split())

现在您可以打印counts 并使用它的方法来获取最常用的单词。

【讨论】:

    【解决方案2】:

    如果您这样做是为了学习目的(即想自己做,而不是使用Counter,这里有一个例子:

    d = {} # Start with an empty ditctionary
    with open(file, 'r', encoding = 'utf-8') as fp:
        lines = fp.readlines()
        for row in lines:
            for word in row.split():
                d[word] = d.get(word,0) + 1 # Insert word into dictionary or update its value
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-03
      • 2014-12-18
      • 1970-01-01
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多