求出现次数最多的单词一共有几种方法,如果要按以下代码接着写,该怎么写?我现在这串代码只能写出出现次数为前三的出现了几次,但是却得不到出现次数最多的三个单词是什么,分别出现了几次。我这里还算出来的就是每个单词出现的次数,但是不会统计出来出现次数最多的三个单词是什么,分别出现了几次。只能得到次数,得不到单词具体是谁。请赐教。
代码如下:
```python
3)求出现次数最多的三个单词(不能包含逗号、句号)
text = "The first step is one of awareness. It will be hard to make a change to positive thinking without being acutely intimate with the thoughts that run through your mind. Recently, I was amazed to discover deep buried emotions from negative thoughts that I had for fewer than 10 minutes. Without awareness, I would have carried the hurt and anger inside. Awareness helped me to bring them out to the open for me to deal with."
lines=text.replace('.','').replace(',','')
lines
words=lines.split()
words
d={}
for i in words:
if i in d:
d[i]+=1
else:
d[i]=1
# sorted(d.values())
sorted(d.values())[-3:]
```
效果如图 :
text = "The first step is one of awareness. It will be hard to make a change to positive thinking without being acutely intimate with the thoughts that run through your mind. Recently, I was amazed to discover deep buried emotions from negative thoughts that I had for fewer than 10 minutes. Without awareness, I would have carried the hurt and anger inside. Awareness helped me to bring them out to the open for me to deal with."
lines = text.replace('.', '').replace(',', '')
words = lines.split()
d = {}
for i in words:
if i in d:
d[i] += 1
else:
d[i] = 1
sorted_words = sorted(d.items(), key=lambda x: x[1], reverse=True)
count = 0
for word, freq in sorted_words:
if count < 3:
print(f"单词 '{word}' 出现了 {freq} 次")
count += 1
else:
break
text = "The first step is one of awareness. It will be hard to make a change to positive thinking without being acutely intimate with the thoughts that run through your mind. Recently, I was amazed to discover deep buried emotions from negative thoughts that I had for fewer than 10 minutes. Without awareness, I would have carried the hurt and anger inside. Awareness helped me to bring them out to the open for me to deal with."
lines = text.replace('.', '').replace(',', '')
words = lines.split()
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
top3 = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)[:3]
for word, count in top3:
print(f"单词 '{word}' 出现了 {count} 次")