2017-08-05 5 views
2

テキストファイルを開いて、各単語が大文字になる回数を数えます。それから私は、上位3回の出現を印刷する必要があります。 このコードは、行内に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 

私はこれを解決するのを助けてください。ありがとうございました!

ありがとうございます。コードを手動でデバッグし、あなたの応答を使用した後、が不要であり、wc[words] = 1が3番目に出現した単語が1回発生すると、プログラムが2倍にカウントすることになりました。 wc[words] = 0に置き換えることで、私はカウントループを避けることができました。

ありがとうございました!

+1

私はあなたには、いくつかのデバッグスキルを学ぶお勧め:

偶然、これは2番目のパラ出力されます。コードに 'print()'ステートメントを追加して、それが何をしているのかを見ることができます。コード内の重要なステップで変数の値を出力します。次に、値が期待どおりかどうかを確認します。また、ソースレベルのデバッガを使用することもできます。 –

+1

カウントが '{'Baa':2、 'Yes':2、 'One':3}'と表示された後、カウントコード 'wc'に何も問題はありません。あなたは2つの 'while'ループでしようとしています(注:両方とも' for'ループでなければなりません)。あなたのロジックが失敗した理由は、2つ目のケースで問題がある '1'より大きい3つ以下の一意の値がある場合、' t3'をリセットすることです。 – AChampion

答えて

4

これは非常に簡単です。しかし、いくつかのツールが必要です。

  1. re.sub、言葉(from collections import Counter最初に行う)をカウントするために、str.istitle

  2. collections.Counterを使用して、表題のケースで単語を除外するために、句読点

  3. filterを取り除きます。


textがあなたのパラ(最初の1)を保持していると仮定すると、これは動作します:

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

x最も一般的な単語を返すCounter.most_common(x)

[('One', 3), ('Baa', 2), ('Yes', 2)] 
関連する問題