python统计字符串中单词出现次数并进行排序
时间: 2023-11-13 10:06:00 浏览: 257
Python统计单词出现的次数
可以使用 Python 中的字典来统计字符串中单词出现次数,并使用 sorted() 函数进行排序。以下是示例代码:
```python
sentence = "hello world this is a test sentence for testing"
# 将字符串转换为单词列表
words = sentence.split()
# 使用字典统计单词出现次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 按单词出现次数进行排序
sorted_words = sorted(word_count.items(), key=lambda x: x[1], reverse=True)
# 输出排序后的单词及其出现次数
for word, count in sorted_words:
print(word, count)
```
输出结果:
```
a 1
for 1
hello 1
is 1
sentence 1
test 1
testing 1
this 1
world 1
```
阅读全文