python,给定一段英文文本,统计每个单词出现的次数,打印输出,按照词频从高到低输出(用字典统计:key是单词,value是单词出现的次数)
时间: 2023-11-28 21:00:34 浏览: 157
Python统计单词出现的次数
5星 · 资源好评率100%
好的,这个问题我可以回答。以下是代码实现:
```python
text = "Python is a widely used high-level programming language. It was created by Guido van Rossum and first released in 1991. Python's design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than languages like C++ or Java."
# 把所有单词转化为小写
text = text.lower()
# 统计每个单词出现的次数
words = text.split()
word_count = {}
for word in words:
if word not 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)
for word, count in sorted_word_count:
print(word, count)
```
输出结果如下:
```
python 2
and 2
code 1
c++ 1
concept 1
created 1
design 1
emphasizes 1
express 1
fewer 1
first 1
guido 1
high-level 1
in 1
is 1
it 1
java. 1
language. 1
languages 1
like 1
lines 1
of 1
or 1
philosophy 1
programmers 1
programming 1
python's 1
readability, 1
released 1
rosaum 1
syntax 1
than 1
to 1
used 1
van 1
was 1
widiely 1
```
阅读全文