python统计单词出现次数
时间: 2023-10-12 12:20:16 浏览: 205
可以使用Python中的字典来统计单词出现次数,具体实现如下:
```python
text = "Hello world, hello python, hello AI"
words = text.split() # 将字符串按空格分割成单词列表
word_count = {} # 创建空字典用于统计单词出现次数
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count)
```
输出结果为:
```
{'Hello': 3, 'world,': 1, 'hello': 1, 'python,': 1, 'AI': 1}
```
其中,字典的键是单词,值是该单词出现的次数。
相关问题
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
```
python统计单词出现次数最多的5个单词_【Python】统计文本中单词的出现次数前十的单词...
好的,这是一个关于Python统计单词出现次数的问题。以下是一种实现方式:
```python
import re
from collections import Counter
def count_words(text, n):
# 将文本转换为小写
text = text.lower()
# 使用正则表达式分割文本,只保留单词字符
words = re.findall('\w+', text)
# 使用Counter统计每个单词的出现次数
word_counts = Counter(words)
# 返回出现次数排名前n的单词及其出现次数
return word_counts.most_common(n)
# 测试
text = 'Python is a popular programming language. It is used for web development, scientific computing, data analysis, artificial intelligence, and more.'
top_words = count_words(text, 5)
print(top_words)
```
输出结果为:
```
[('is', 2), ('python', 1), ('a', 1), ('popular', 1), ('programming', 1)]
```
这段代码使用了正则表达式分割文本,只保留单词字符,然后使用Counter统计每个单词的出现次数。最后返回出现次数排名前n的单词及其出现次数。