2016-11-30 101 views
5

新程序员在这里。目前,我有一本包含所有年份的程序字典,每年的文献中总共使用了多少个词汇。我应该在这里使用哪种数据结构?

我现在需要做的是通过查找用户提供的特定词汇来找出所在年份的相对频率。通过计算特定单词的使用次数并将其除以当年使用的单词总量,找到相对频率。

我是否需要制作另一个字典,其中包含该年份以及该字词在当年使用的次数?或者完全不同的数据结构?我还应该提到用户提供了开始日期和结束日期。

以下是我目前使用的字典的功能。如果你对如何改善这一点有什么建议,我全都是耳朵!

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() 
+0

哪里是使用每个特定单词多少次的信息源? – TigerhawkT3

+0

很好的你作为一名新程序员思考数据结构。最好的答案取决于你没有提到的其他因素:数据是动态的还是静态的?它有多大,性能有多重要? – wim

+0

@ TigerhawkT3它在另一个文件提供给我,我还没有切片。 – Blakester

回答

0

我假设你没有很多年(可能高达几百),所以我期望列表和字典具有相似的查找时间。但是,字典在语义上更方便。同时,在每年你可能有很多单词,所以最好使用具有常量(O(1))查找的结构,因此它是。

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]['']