使用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' 11 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 查找替换- 选择· 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-20 22:38:39 浏览: 107
以下是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' 11 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 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."
# 去除标点符号和换行符
import re
text = re.sub(r'[^\w\s]', '', text)
text = re.sub(r'\n', '', text)
# 将文本转化为小写字母
text = text.lower()
# 将文本分割为单词列表
words = text.split()
# 统计单词出现频率
freq_dict = {}
for word in words:
if word in freq_dict:
freq_dict[word] += 1
else:
freq_dict[word] = 1
# 按照单词出现频率排序
sorted_freq = sorted(freq_dict.items(), key=lambda x: x[1], reverse=True)
# 输出前十个单词
print(dict(sorted_freq[:10]))
```
输出结果为:
```
{'you': 7, 'the': 6, 'not': 4, 'be': 4, 'can': 3, 'do': 3, 'if': 2, 'like': 2, 'and': 2, 'he': 2}
```
其中,字典中的键为单词,值为该单词出现的频率。可以看到,出现频率最高的单词为“you”,共出现了7次。
阅读全文