【发布时间】:2020-06-18 23:01:20
【问题描述】:
我必须打开一个文本文件,然后计算每个单词大写的次数。然后我需要打印前 3 次出现。 这段代码一直有效,直到它得到一个文本文件,其中的单词在一行中加倍。
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,我能够避免出现计数循环。
谢谢!
【问题讨论】:
-
我建议你学习一些调试技巧。您可以将
print()语句添加到您的代码中以查看它在做什么。在代码中的关键步骤打印出变量的值。然后检查这些值是否符合您的预期。或者,您可以使用源代码级调试器。 -
在计数显示
{'Baa': 2, 'Yes': 2, 'One': 3}之后计数代码wc没有任何问题,但是在我很困惑之后你的逻辑 - 你想用 2 个while循环做什么(注意:它们都应该是for循环)。你的逻辑失败的原因是你重置t3,如果有少于3个唯一值大于1,这在你的第二种情况下是问题。
标签: python python-3.x