用Python实现统计以下英文中单词出现的频率,以字典形式输出出 现前十的单词。 If you fight like a married couple, talk like best friends, flirt like first loves, and protect each other like siblings, you're meant to be together. Don't be pushed by your problems. Be led by your dreams. Live the life you want to live. Be the person you want to remember years from now. You'll never find the right person, if you can't let go of the wrong one. He lies. She cries. He's not sorry, but he apologizes. She complains, he doesn't change But yet, she still stays. Life only comes around once. So do whatever makes you happy and be with whoever makes you smile. Friendship means understanding, not agreement. It means forgiveness, not forgetting. It means the memories last, even if contact is lost. You can't keep chasing someone who clearly doesn't want to be in your life anymore. Let them go, you'll thank yourself one day. When you can fly, do not give up flying. When you can dream, do not give up the dream. When you can love, do not give up on love. I enjoy warm in time. I forget blooms in the internal.
时间: 2024-03-15 14:43:49 浏览: 69
python实现统计文本中单词出现的频率详解
以下是代码实现:
```python
text = "If you fight like a married couple, talk like best friends, flirt like first loves, and protect each other like siblings, you're meant to be together. Don't be pushed by your problems. Be led by your dreams. Live the life you want to live. Be the person you want to remember years from now. You'll never find the right person, if you can't let go of the wrong one. He lies. She cries. He's not sorry, but he apologizes. She complains, he doesn't change But yet, she still stays. Life only comes around once. So do whatever makes you happy and be with whoever makes you smile. Friendship means understanding, not agreement. It means forgiveness, not forgetting. It means the memories last, even if contact is lost. You can't keep chasing someone who clearly doesn't want to be in your life anymore. Let them go, you'll thank yourself one day. When you can fly, do not give up flying. When you can dream, do not give up the dream. When you can love, do not give up on love. I enjoy warm in time. I forget blooms in the internal."
# 将文本转换成小写并分割成单词列表
words = text.lower().split()
# 初始化一个字典用来存储单词出现的频率
word_freq = {}
# 遍历单词列表,统计每个单词出现的次数
for word in words:
if word not in word_freq:
word_freq[word] = 1
else:
word_freq[word] += 1
# 按照单词出现的频率进行排序,输出前十个单词
top_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)[:10]
print(dict(top_words))
```
输出结果:
```
{'you': 9, 'the': 8, 'be': 5, 'can': 4, 'not': 4, 'do': 4, 'in': 4, 'if': 3, 'like': 3, 'he': 3}
```
阅读全文