python 统计单词出现的次数
时间: 2023-10-13 19:28:35 浏览: 44
可以使用 Python 的字典(dictionary)来统计单词出现的次数。具体操作如下:
```python
text = "This is a sample text with several words and repeated words"
words = text.split() # 将文本按空格分割成单词列表
word_count = {} # 创建空字典
# 遍历单词列表,统计每个单词出现的次数
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 打印每个单词及其出现次数
for word, count in word_count.items():
print(word, count)
```
输出结果为:
```
This 1
is 1
a 1
sample 1
text 1
with 1
several 1
words 2
and 1
repeated 1
```
相关问题
python统计单词出现次数
可以使用Python中的字典来统计单词出现的次数,具体步骤如下:
1. 读取文本文件,将文本内容存储到一个字符串中。
2. 将字符串转换为单词列表,可以使用split方法将字符串按空格分割成单词。
3. 遍历单词列表,使用字典来统计每个单词出现的次数,如果单词已经在字典中,则将其计数加1,否则将其添加到字典中,并初始化计数为1。
4. 最后输出字典中每个单词出现的次数。
下面是一个简单的实现示例:
```python
# 读取文本文件
with open('test.txt') as f:
text = f.read()
# 将字符串转换为单词列表
word_list = text.split()
# 统计单词出现次数
word_count = {}
for word in word_list:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 输出结果
for word, count in word_count.items():
print(word, count)
```
注意,上述代码只是一个简单的示例,实际统计单词出现次数时,可能需要考虑一些特殊情况,比如大小写、标点符号等。
python统计单词出现的次数
以下是使用Python统计单词出现次数的例子:
```python
# 定义一个函数来统计单词出现的次数
def count_words(text):
# 创建一个空字典来存储单词和对应的出现次数
word_count = {}
# 将文本转换为小写,并按空格分割成单词列表
words = text.lower().split()
# 遍历单词列表
for word in words:
# 如果单词已经在字典中,则将其出现次数加1
if word in word_count:
word_count[word] += 1
# 如果单词不在字典中,则将其添加到字典,并将出现次数设置为1
else:
word_count[word] = 1
# 返回统计结果
return word_count
# 调用函数并传入文本
text = "This is a sample text. It contains some words. This is just an example."
result = count_words(text)
# 打印统计结果
for word, count in result.items():
print(f"{word}: {count}")
```
输出结果为:
```
this: 2
is: 2
a: 1
sample: 1
text.: 1
it: 1
contains: 1
some: 1
words.: 1
just: 1
an: 1
example.: 1
```