python - 如何编写测量每行(对象)频率的函数 - Python

标签 python python-3.x

编写一个函数 create_dictionary(filename) 来读取指定文件并返回从对象名称到出现次数(猜测特定对象的次数)的字典映射。例如,给定一个包含以下内容的文件 mydata.txt:

abacus
calculator
modern computer
abacus
modern computer
large white thing
modern computer

所以,当我输入这个时:

dictionary = create_dictionary('mydata.txt')
for key in dictionary:
print(key + ': ' + str(dictionary[key]))

该函数必须返回以下字典格式:

{'abacus': 2, 'calculator': 1, 'modern computer': 3, 'large white thing': 1}

除此之外,我还知道如何计算单词的频率。但是如何计算上述每一行的频率呢?

以下是一些限制:

  • 您可以假设给定的文件存在,但它可能是空的(即 不包含行)。
  • 键必须按照它们出现的顺序插入到字典中 出现在输入文件中。
  • 在某些测试中,我们按插入顺序显示键;在其他情况下,按字母顺序对键进行排序。
  • 应从对象名称中删除前导和尾随空格
  • 空对象名称(例如空行或只有空格的行) 应该被忽略。

最佳答案

一种更简单的实现方法是使用以下内容

设文件名为a.txt

from collections import Counter
s = open('a.txt','r').read().strip()
print(Counter(s.split('\n')))

输出如下:

Counter({'abacus': 2,
         'calculator': 1,
         'large white thing': 1,
         'modern computer': 3})

关于python - 如何编写测量每行(对象)频率的函数 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52474374/

相关文章:

python - 矩阵中列的最大值列表(没有 Numpy)

python - 破坏了 Ubuntu 16.04 (AWS EC2) 上的 python 依赖关系

python - Pandas 用 df.drop 删除行不起作用

python - str在Python中是如何实现的?

读取输入时出现 Python EOF 错误

python - 在 Python 中仅打印以逗号和空格分隔的列表中的数值

python - 使用带有字典参数的@functools.lru_cache

python - 将矩阵转换为对角矩阵

python - 如何在 Python 中找到与谓词匹配的序列中的第一个元素?

python - 获取具有元类的类的名称