2017-03-27 42 views
1

我有一個語料庫,它是一個元組列表,包含一個單詞和一個POS標籤的元組。我現在的問題是給出語料庫中存在的每個單詞和每個POS標籤,遍歷該語料庫並記錄每個單詞和標籤組合存在於語料庫中的時間量。如果單詞和標籤組合不會在語料庫存在使得計數爲0Python 3 - 遍歷整個語料庫並記錄它的計數

 possible_tags = ['Verb','Noun','Det'] 

    possible_words = ['Merger', 'proposed', 'Wards', 'protected', 'A'] 

    corpus = [('Merger', 'Noun'), ('proposed', 'Verb'), ('Wards', 'Noun'), ('protected', 'Verb'), ('A', 'Det'), ('Merger','Noun')] 

    output = {'Merger_Noun':2, 'Merger_Verb':0, 'Merger_Det':0, 'proposed_Noun':0, 'proposed_Verb':1, 'proposed_Det':0, ....... } 

回答

1

想盡轉換爲一個字典,使其更容易。

possible_tags = ['Verb','Noun','Det'] 

possible_words = ['Merger', 'proposed', 'Wards', 'protected', 'A'] 

corpus = [('Merger', 'Noun'), ('proposed', 'Verb'), ('Wards', 'Noun'), ('protected', 'Verb'), ('A', 'Det'), ('Merger','Noun')] 

#Initialize output to empty dictionary 
output = {} 

//dictionary initialization. 

for each_word in possible_words: 
    for each_tag in possible_tags: 
     key = each_word + "_" + each_tag 
     output[key] = 0 


#iterate through corpus 
for each in corpus: 
    #extract each tuple, and update dictionary with keys as string and count as integer 
    output[each[0] +"_"+each[1]] += 1 
+0

嗨,謝謝你的迴應,但這個解決方案並沒有解決我所有的問題。解決方案的輸出僅打印語料庫中的word_tag組合。我也希望word_tag組合不在語料庫中,它們的計數應該是0 –

+0

在執行此操作之前,您可以使用所有可能的組合初始化空字典。 – sai

+0

我更新了空字典的初始化代碼。讓我知道它是否有幫助。 – sai