python统计字符串中有多少个单词
时间: 2023-04-26 21:02:09 浏览: 256
可以使用Python中的split()函数将字符串分割成单词,然后统计单词的数量即可。具体代码如下:
```python
s = "Python is a powerful programming language"
words = s.split()
print(len(words)) # 输出:6
```
其中,split()函数默认以空格作为分隔符,将字符串分割成单词,并返回一个包含所有单词的列表。使用len()函数统计列表中元素的数量,即可得到字符串中单词的数量。
相关问题
python统计字符串中单词个数代码
下面是 Python 统计字符串中单词个数的代码:
```
def count_words(text):
words = text.split()
return len(words)
```
你可以将文本作为参数传递给 count_words() 函数,然后函数将根据空格来拆分文本并计算单词个数。
python 统计字符串中每个单词出现的次数
可以使用 Python 的 Counter 类来统计字符串中每个单词出现的次数,具体代码如下:
```python
from collections import Counter
s = "This is a test string. This string is a test."
words = s.split()
word_counts = Counter(words)
print(word_counts)
```
输出结果为:
```
Counter({'This': 2, 'is': 2, 'a': 2, 'test': 2, 'string.': 1, 'string': 1})
```
其中,Counter 类会返回一个字典,其中键为单词,值为该单词在字符串中出现的次数。