2017-08-05 26 views
2

我必須做一個任務,我打開一個文本文件,然後計算每個單詞大寫的次數。然後我需要打印前三個事件。 這段代碼可以工作,直到它得到一個文本文件,其中的文字在一行中翻倍。計算一段文字中最常見的名詞詞彙

txt文件1:

Jellicle Cats are black and white, 
Jellicle Cats are rather small; 
Jellicle Cats are merry and bright, 
And pleasant to hear when they caterwaul. 
Jellicle Cats have cheerful faces, 
Jellicle Cats have bright black eyes; 
They like to practise their airs and graces 
And wait for the Jellicle Moon to rise. 

結果:

6 Jellicle 
5 Cats 
2 And 

txt文件2:

Baa Baa black sheep have you any wool? 
Yes sir Yes sir, wool for everyone. 
One for the master, 
One for the dame. 
One for the little boy who lives down the lane. 

結果:

1 Baa 
1 One 
1 Yes 
1 Baa 
1 One 
1 Yes 
1 Baa 
1 One 
1 Yes 

這是我的代碼:

wc = {} 
t3 = {} 
p = 0 
xx=0 
a = open('novel.txt').readlines() 
for i in a: 
    b = i.split() 
    for l in b: 
    if l[0].isupper(): 
     if l not in wc: 
     wc[l] = 1 
     else: 
     wc[l] += 1 
while p < 3: 
    p += 1 
    max_val=max(wc.values()) 
    for words in wc: 
    if wc[words] == max_val: 
     t3[words] = wc[words] 
     wc[words] = 1 

    else: 
     null = 1 
while xx < 3: 
    xx+=1 
    maxval = max(t3.values()) 
    for word in sorted(t3): 
    if t3[word] == maxval: 
     print(t3[word],word) 
     t3[word] = 1 
    else: 
     null+=1 

請幫我解決這個問題。謝謝!

謝謝你的所有建議。在手動調試代碼以及​​使用您的響應後,我能夠發現while xx < 3:是不必要的,以及wc[words] = 1最終使得程序對單詞進行雙重計數,如果發生第三個最多的單詞出現一次。用wc[words] = 0取代它,我可以避免出現計數循環。

謝謝!

+1

我建議你學習一些調試技巧。你可以在你的代碼中添加'print()'語句來查看它正在做什麼。在代碼中的關鍵步驟打印出變量的值。然後檢查這些值是否符合您的預期。或者,您可以使用源代碼級調試器。 –

+1

計數顯示'{'Baa':2,'Yes':2,'One':3}'之後,計數代碼'wc'沒有什麼問題,但是我很困惑 - 你的邏輯是 - 什麼是你試圖用2'while'循環(注意:它們都應該是'for'循環)。你的邏輯失敗的原因是你重置't3',如果有少於3個唯一值大於'1',在你的第二種情況是這個問題。 – AChampion

回答

4

這非常簡單。但是你需要一些工具。

  1. re.sub,擺脫標點符號

  2. filter,採用str.istitle

  3. collections.Counter,來算的話,以過濾掉標題案字(做from collections import Counter第一)。


假設text握着你對(第一個),這個工程:

In [296]: Counter(filter(str.istitle, re.sub('[^\w\s]', '', text).split())).most_common(3) 
Out[296]: [('Jellicle', 6), ('Cats', 5), ('And', 2)] 

Counter.most_common(x)返回x最常用的詞。

巧合的是,這是你的第二個段輸出:

[('One', 3), ('Baa', 2), ('Yes', 2)] 
相關問題