python统计字符串中单词的个数
时间: 2023-08-31 09:09:28 浏览: 165
可以使用 Python 的字符串和列表操作来统计字符串中单词的个数,例如:
```python
string = "This is a string with some words."
word_list = string.split()
word_count = len(word_list)
print("The string has", word_count, "words.")
```
运行结果为:
```
The string has 6 words.
```
注意,此处的统计方法比较简单,可能无法处理所有情况,例如对于包含缩写、特殊字符等的复杂字符串可能会产生误差。
相关问题
python统计输入字符串中单词的个数
可以使用Python中的split()函数将输入字符串分割成单词列表,然后使用len()函数统计列表中单词的个数。具体代码如下:
```
input_str = input("请输入字符串:")
word_list = input_str.split()
word_count = len(word_list)
print("单词个数为:", word_count)
```
统计字符串中单词的个数
以下是两种统计字符串中单词个数的方法:
方法一:使用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