统计输出字符串中单词的个数
时间: 2023-09-01 19:07:33 浏览: 84
可以使用字符串的 split() 方法将字符串拆分成单词,然后再统计单词的个数。例如:
```python
s = "Hello world! This is a test string."
words = s.split()
num_words = len(words)
print(num_words) # 输出:7
```
上面的代码中,将字符串 s 拆分成单词,存储在列表 words 中,然后用 len() 函数统计列表中元素的个数,即单词的个数。注意,split() 方法默认以空格作为分隔符,如果字符串中有其他分隔符,需要在调用时指定。
相关问题
统计字符串中单词的个数
以下是两种统计字符串中单词个数的方法:
方法一:使用Shell命令
```shell
echo "This is a test sentence." | wc -w
```
输出:4
方法二:使用Python
```python
string = "This is a test sentence."
word_list = string.split()
print(len(word_list))
```
输出:4
用函数统计字符串中单词的个数
好的,这是一个技术问题,我可以为您提供答案。
以下是一段 Python 代码,利用正则表达式实现统计字符串中单词的个数:
```python
import re
def count_words(text):
words = re.findall(r'\w+', text)
return len(words)
```
使用示例:
```python
text = 'Hello World! This is a sample text.'
print(count_words(text)) # 输出 7
```
请注意,这段代码仅适用于英文字符串,对于其他语言可能需要相应地修改正则表达式。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)