2016-11-30 106 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]['']