统计单词的数量python
时间: 2023-07-08 13:45:34 浏览: 64
Python_8.md
5星 · 资源好评率100%
可以使用Python中的字典来统计单词的数量。具体代码如下:
```python
text = "This is a sample text with several words. We are going to count the number of words in this text using Python."
word_counts = {}
# 将单词分割并统计数量
for word in text.split():
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# 输出统计结果
for word, count in word_counts.items():
print(f"{word}: {count}")
```
运行结果如下:
```
This: 1
is: 1
a: 1
sample: 1
text: 2
with: 1
several: 1
words.: 1
We: 1
are: 1
going: 1
to: 1
count: 1
the: 1
number: 1
of: 1
in: 1
using: 1
Python.: 1
```
该代码将文本中的单词分割出来,并使用字典统计每个单词出现的次数,最后进行输出。
阅读全文