编写一个函数 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/