str_a="python python is good and python is easy",求字符串中每个单词出现的次数
时间: 2024-03-23 17:41:30 浏览: 15
可以通过 Python 的 Counter 类来统计字符串中每个单词出现的次数。具体代码如下:
```python
from collections import Counter
str_a = "python python is good and python is easy"
# 将字符串转换为单词列表
word_list = str_a.split()
# 使用 Counter 统计每个单词出现的次数
word_count = Counter(word_list)
# 输出结果
for word, count in word_count.items():
print(f"{word}: {count}")
```
输出结果为:
```
python: 3
is: 2
good: 1
and: 1
easy: 1
```
其中,Counter 类可以接受一个可迭代对象作为参数,返回一个计数器字典,其中每个元素都是可迭代对象中的一个元素及其出现次数的键值对。我们将字符串转换为单词列表,然后使用 Counter 统计每个单词出现的次数,并输出结果。
相关问题
用python实现输入一段字符串统计每个单词出现的次数
好的,可以使用Python的字典来实现这个功能。代码如下:
```python
# 获取用户输入的字符串
input_str = input('请输入一段字符串:')
# 将字符串按空格分割成单词列表
words = input_str.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)
```
这段代码会先让用户输入一段字符串,然后将字符串按空格分割成单词列表。接下来,我们创建一个空字典 `word_count`,用于统计每个单词出现的次数。然后,我们遍历单词列表,对于每个单词,如果它已经在字典中出现过,就将它的计数加一,否则就将它添加到字典中,并将计数设置为一。最后,我们遍历字典,输出每个单词出现的次数。
输入字符串,输出字符串中出现次数最多的单词python
您好,我是 ChitGPT,我可以回答您的问题。关于输入字符串并输出其中出现次数最多的单词 Python,您可以使用 Python 编程语言来实现。
以下是一个示例代码,它使用 Python 中的 Counter 类和 split() 方法,找到输入字符串中出现次数最多的单词:
```
from collections import Counter
input_str = "Python is a popular programming language used for web development, scientific computing, artificial intelligence, and more."
# 将字符串按照空格分割成单词列表
words = input_str.split()
# 使用 Counter 类统计单词出现次数
word_counts = Counter(words)
# 找到出现次数最多的单词
most_common_word = word_counts.most_common(1)[0][0]
print("出现次数最多的单词是:", most_common_word)
```
希望能够帮助您解决问题!