7-3 jmu-Java&Python-统计一段文字中的单词个数并按单词的字母顺序排序后输出
时间: 2024-06-13 14:09:10 浏览: 136
Python大作业之jmu-java&python-统计字符个数.txt
以下是Python统计一段文字中的单词个数并按单词的字母顺序排序后输出的代码:
```python
text = "This is a sample text with several words. We will count the number of words and sort them alphabetically."
# 将所有单词转换为小写并分割成列表
words = text.lower().split()
# 统计每个单词出现的次数
word_count = {}
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
# 按字母顺序排序并输出
sorted_words = sorted(word_count.keys())
for word in sorted_words:
print(word, word_count[word])
```
运行以上代码,将会输出每个单词及其出现的次数,按字母顺序排序。
阅读全文