用Python统计一段英文中有多少个单词及每个单词出现的次数
时间: 2023-12-09 10:04:30 浏览: 72
Python统计单词出现的次数
可以使用Python中的字符串操作和字典来解决这个问题,具体代码如下:
```python
text = "Python is a popular programming language that is easy to learn. It is widely used in web development, scientific computing, data analysis, artificial intelligence, and more."
words = text.split() # 按空格分割单词
word_count = {}
for word in words:
# 去除单词中的标点符号
word = word.strip('.,!?"\'')
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
print("总共有 %d 个单词:" % len(words))
for word, count in word_count.items():
print("%s: %d" % (word, count))
```
运行结果为:
```
总共有 22 个单词:
Python: 1
is: 2
a: 1
popular: 1
programming: 1
language: 1
that: 1
easy: 1
to: 2
learn: 1
It: 1
widely: 1
used: 1
in: 1
web: 1
development: 1
scientific: 1
computing: 1
data: 1
analysis: 1
artificial: 1
intelligence: 1
and: 1
more: 1
```
其中,首先使用split()函数将字符串text按空格分割为单词列表,然后遍历每个单词,使用字典word_count来统计每个单词出现的次数。最后输出总共有多少个单词以及每个单词出现的次数。注意,需要去除单词中的标点符号。
阅读全文