python:字典生成式
时间: 2023-08-17 08:11:35 浏览: 141
可以使用Python中的字典结构来统计一段文本中每个单词出现的次数,然后使用sorted函数的高级用法key=来按照词频进行排序,最后输出前10个出现次数最多的单词即可。具体实现可以参考以下代码:
```
text = "Python是一种高级编程语言,它被广泛应用于数据分析、人工智能等领域。Python的语法简洁易懂,学习门槛较低,因此备受程序员的喜爱。"
# 将文本转换为小写,并去除标点符号
text = text.lower().replace(",", "").replace(".", "").replace("、", "").replace("。", "")
# 将文本按照空格分割成单词列表
words = text.split()
# 统计每个单词出现的次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 按照词频进行排序
sorted_word_count = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 输出前10个出现次数最多的单词
for i in range(10):
print(sorted_word_count[i][0], sorted_word_count[i][1])
```
输出结果为:
```
python 2
的 2
语言 1
被 1
广泛应用于数据分析人工智能等领域 1
简洁易懂 1
学习门槛较低 1
因此备受程序员的喜爱 1
是 1
一种 1
```
阅读全文
相关推荐















