已知字符串words中存放了若干以空格分隔的单词,如words=’hello python hello world hello china good china’,统计每个单词出现的次数。
时间: 2023-12-03 12:43:37 浏览: 66
可以使用Python中的字典来实现单词计数,具体实现如下:
```python
words = 'hello python hello world hello china good china'
word_list = words.split() # 将字符串按空格分割成单词列表
word_count = {} # 用字典存储单词计数结果
for word in word_list:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
print(word_count)
```
运行结果如下:
```
{'hello': 3, 'python': 1, 'world': 1, 'china': 2, 'good': 1}
```
其中,字典`word_count`的键为单词,值为该单词出现的次数。在循环中,如果单词已经在字典中存在,则将该单词对应的值加1;否则,将该单词加入字典并将其值设为1。最终输出字典即可。
相关问题
python已知一个字符串中存放了若干用空格分隔的单词,统计每个单词出现的次数。
可以使用Python中的字典来实现单词计数。具体步骤如下:
1. 将字符串按照空格分割成单词列表。
2. 遍历单词列表,对于每个单词,如果该单词已经在字典中,将该单词计数加1,否则将该单词添加到字典中,并将其计数初始化为1。
3. 最后遍历字典,输出每个单词及其对应的计数。
下面是使用Python实现的代码示例:
```python
string = "hello world hello python world"
word_list = string.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)
```
输出结果:
```
hello 2
world 2
python 1
```
已知字符串str= skdaskerkjsalkj ,请使用Python统计该字符串中各字母出现的次数。
好的,我可以回答这个问题。以下是代码:
```python
str = "skdaskerkjsalkj"
freq = {}
for char in str:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
print(freq)
```
该代码中,我们遍历字符串中的每一个字符,如果字符在字典中已存在,则将该字符的计数器加1,否则就将该字符添加到字典中,并将其计数器初始化为1。最后,输出字典freq,其中存储了每个字符出现的次数。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)