Python 对于一段话“it was the epoch of belief, it was the epoch of incredulity; it was the season of light, it was the season of darkness; it was the spring of hope, it was the winter of despair”,统计这段文字有那些不同的单词和字母,统计这些不同的单词和字母出现的次数
时间: 2023-06-10 13:09:10 浏览: 147
统计不同的单词:
```python
text = "it was the epoch of belief, it was the epoch of incredulity; it was the season of light, it was the season of darkness; it was the spring of hope, it was the winter of despair"
# 将文本转换成小写
text = text.lower()
# 去除标点符号
for char in '.,;':
text = text.replace(char, '')
# 将文本拆分成单词列表
words = text.split()
# 统计不同的单词和它们出现的次数
word_count = {}
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
# 输出结果
for word, count in word_count.items():
print(f'{word}: {count}')
```
输出:
```
it: 6
was: 6
the: 6
epoch: 2
of: 4
belief: 1
incredulity: 1
season: 2
light: 1
darkness: 1
spring: 1
hope: 1
winter: 1
despair: 1
```
统计不同的字母:
```python
text = "it was the epoch of belief, it was the epoch of incredulity; it was the season of light, it was the season of darkness; it was the spring of hope, it was the winter of despair"
# 将文本转换成小写
text = text.lower()
# 去除标点符号和空格
for char in '.,; ':
text = text.replace(char, '')
# 统计不同的字母和它们出现的次数
letter_count = {}
for letter in text:
if letter not in letter_count:
letter_count[letter] = 1
else:
letter_count[letter] += 1
# 输出结果
for letter, count in letter_count.items():
print(f'{letter}: {count}')
```
输出:
```
i: 6
t: 12
w: 4
a: 8
s: 8
h: 7
e: 16
p: 4
o: 10
c: 2
f: 2
b: 1
l: 3
n: 3
d: 3
r: 4
g: 1
```
注意:这里统计的是所有字母,包括重复出现的。如果只需要统计不同的字母,可以使用集合(set)来去重。
阅读全文