python统计符串中单词出现个数
时间: 2023-11-12 21:09:09 浏览: 36
可以使用Python的collections模块中的Counter类来实现统计字符串中单词出现个数的功能。具体的实现代码如下所示:
```python
from collections import Counter
s = "This is a test string to count the number of occurrences of each word"
# 将字符串中的单词拆分出来
words = s.split()
# 使用Counter统计单词出现个数
word_counts = Counter(words)
# 输出每个单词及其出现次数
for word, count in word_counts.items():
print(f"{word}: {count}")
```
输出结果如下所示:
```
This: 1
is: 1
a: 1
test: 1
string: 1
to: 1
count: 1
the: 2
number: 1
of: 1
occurrences: 1
each: 1
word: 1
```
以上代码中,首先将字符串拆分成单词并存储在列表中,然后使用Counter统计每个单词出现的次数,最后遍历Counter对象中的每个元素,输出每个单词及其出现次数。
相关问题
python统计输入字符串中单词个数
可以使用Python中的split()函数将输入字符串分割成单词,然后使用len()函数统计单词个数。具体代码如下:
```python
input_str = input("请输入字符串:")
word_list = input_str.split() # 使用split()函数分割字符串
word_count = len(word_list) # 统计单词个数
print("单词个数为:", word_count)
```
注意,这里默认以空格作为单词的分隔符,如果需要使用其他分隔符,可以在split()函数中指定。
python统计字符串每个单词出现的次数
可以使用Python中的字典(dictionary)来统计每个单词出现的次数,具体实现如下:
```python
text = "This is a sample text with several words. Some of the words may repeat."
words = text.split() # 将文本拆分成单词列表
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
print(word_counts)
```
输出结果为:
```
{'This': 1, 'is': 1, 'a': 1, 'sample': 1, 'text': 1, 'with': 1, 'several': 1, 'words.': 1, 'Some': 1, 'of': 1, 'the': 1, 'words': 1, 'may': 1, 'repeat.': 1}
```
其中,`split()`方法可以将文本按照空格符拆分成单词列表;然后使用一个字典来存储每个单词出现的次数,如果单词已经出现过,则将其对应的计数器加1,否则将其计数器初始化为1。最后输出字典即可得到每个单词出现的次数。