这里是新程序员。目前,我的程序有一本字典,其中包含所有年份以及每年在文学中使用了多少个单词。
我现在需要做的是通过查找用户给出的特定词来找到所述年份的相对频率。相对频率的计算方法是将特定单词的使用次数除以当年使用的单词总数。
我是否需要制作另一本包含年份和该词在该年使用次数的词典?还是完全不同的数据结构?我还应该提到,用户提供了开始日期和结束日期。
下面是我目前拥有的字典的功能。如果您对如何改进它也有任何建议,我会洗耳恭听!
yearTotal = dict()
def addTotal():
with open('total_counts.csv') as allWords:
readW = csv.reader(allWords, delimiter=',')
for row in readW:
yearTotal[row[0]] = row[1]
addTotal()
最佳答案
我假设您没有很多年(可能最多几百年),所以我希望列表和字典具有相似的查找时间。然而,字典在语义上更方便。
同时,每年你可能有很多单词,所以最好使用具有常量 (O(1)) 查找的结构,所以 dict 就是这样。
from collections import defaultdict
yearTotal = defaultdict(labda: defaultdict(int))
fh = open('total_counts.csv')
for year, word in csv.reader(fh, delimiter=","):
yearTotal[year][''] += 1 # here we'll cache the number of words
yearTotal[year][word] += 1
# ...
word = "foo"
year = "1984"
relative_frequency = float(yearTotal[year][word]) / yearTotal[year]['']
关于python - 我应该在这里使用哪种数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40899153/