テキストファイルを開いて、各単語が大文字になる回数を数えます。それから私は、上位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
に置き換えることで、私はカウントループを避けることができました。
ありがとうございました!
私はあなたには、いくつかのデバッグスキルを学ぶお勧め:
偶然、これは2番目のパラ出力されます。コードに 'print()'ステートメントを追加して、それが何をしているのかを見ることができます。コード内の重要なステップで変数の値を出力します。次に、値が期待どおりかどうかを確認します。また、ソースレベルのデバッガを使用することもできます。 –
カウントが '{'Baa':2、 'Yes':2、 'One':3}'と表示された後、カウントコード 'wc'に何も問題はありません。あなたは2つの 'while'ループでしようとしています(注:両方とも' for'ループでなければなりません)。あなたのロジックが失敗した理由は、2つ目のケースで問題がある '1'より大きい3つ以下の一意の値がある場合、' t3'をリセットすることです。 – AChampion