【发布时间】:2018-10-21 05:43:04
【问题描述】:
def get_word_frequencys(words):
"""given a list of words, returns a dictionary of the words,
and their frequencys"""
words_and_freqs = {}
for word in words:
words_and_freqs[word] = words.count(word)
return words_and_freqs
上述函数适用于小文件,但是,我需要它来处理 264505 字长的文件,目前,我的程序需要几分钟才能处理这种大小的文件。
如何以更有效的方式构建字典?
所有相关代码:
def main(words):
"""
given lots of words do things
"""
words_and_frequencys = get_word_frequencys(words)
print("loaded ok.")
print()
print_max_frequency(words, words_and_frequencys)
def get_word_frequencys(words):
"""given a list of words, returns a dictionary of the words,
and their frequencys"""
words_and_freqs = {}
for word in words:
words_and_freqs[word] = words.count(word)
return words_and_freqs
def print_max_frequency(words, words_and_frequencys):
"""given a dict of words and their frequencys,
prints the max frequency of any one word"""
max_frequency = 0
for word in words:
if words_and_frequencys.get(word) > max_frequency:
max_frequency = words_and_frequencys.get(word)
print(" " + "Maximum frequency = {}".format(max_frequency))
注意对于那些建议使用 Counter 而不是 Count() 的人,我不允许导入除 os 和 re 之外的任何模块。
【问题讨论】:
-
抱歉,已修改。
-
请包含您加载文件并使用此功能的代码
标签: python python-3.x