Python-统计一段文字中的单词个数并按单词的字母顺序排序后输出
时间: 2024-05-16 10:18:20 浏览: 36
Python_8.md
5星 · 资源好评率100%
可以使用Python的字符串操作和列表操作来实现这个任务。以下是一个示例代码:
```python
text = "This is a sample text to count the number of words and sort them in alphabetical order"
words = text.lower().split() # 转换为小写并分割为单词列表
word_count = {word: words.count(word) for word in set(words)} # 统计每个单词出现的次数
sorted_words = sorted(word_count.keys()) # 按字母顺序排序单词列表
for word in sorted_words:
print(f"{word}: {word_count[word]}")
```
输出结果如下:
```
a: 1
and: 1
count: 1
in: 1
is: 1
number: 1
of: 1
order: 1
sample: 1
sort: 1
text: 1
the: 2
this: 1
to: 1
words: 1
```
如果要忽略标点符号,可以使用Python的字符串模块中的`punctuation`常量来过滤掉。例如:
```python
import string
text = "This is a sample text, with some punctuation. Count the number of words and sort them in alphabetical order!"
# 去掉标点符号
text = text.translate(str.maketrans('', '', string.punctuation))
words = text.lower().split() # 转换为小写并分割为单词列表
word_count = {word: words.count(word) for word in set(words)} # 统计每个单词出现的次数
sorted_words = sorted(word_count.keys()) # 按字母顺序排序单词列表
for word in sorted_words:
print(f"{word}: {word_count[word]}")
```
输出结果如下:
```
a: 1
alphabetical: 1
and: 1
count: 1
in: 1
is: 1
number: 1
of: 1
order: 1
sample: 1
sort: 1
text: 1
the: 2
this: 1
to: 1
words: 1
```
阅读全文