统计文本中单词数python
时间: 2023-10-23 15:37:39 浏览: 44
可以使用Python中的split()函数和len()函数来统计文本中单词的数量。具体实现代码如下:
```python
text = "Hello world! This is a sample text for word count."
word_count = len(text.split())
print("The number of words in the text is:", word_count)
```
输出结果为:
```
The number of words in the text is: 10
```
其中,split()函数将文本按照空格分割成单词的列表,len()函数统计单词列表的长度即为单词数。
相关问题
python统计文本中单词数
可以使用Python的正则表达式和字符串操作来统计文本中单词数。以下是一个简单的示例代码:
```python
import re
text = "This is a sample text with multiple words. Counting the number of words in this text is a simple task."
# 使用正则表达式将文本中的单词分离出来
words = re.findall(r'\w+', text)
# 统计单词数量
word_count = len(words)
print("Number of words in the text:", word_count)
```
输出结果为:
```
Number of words in the text: 18
```
该代码使用正则表达式 `\w+` 来匹配文本中的单词,然后使用 Python 的 `len()` 函数计算单词数量。
python统计文本中单词个数
可以通过Python的字符串操作和正则表达式来统计文本中单词的个数。下面是一个简单的实现:
```python
import re
def count_words(text):
words = re.findall(r'\w+', text.lower())
return len(words)
text = "Python是一种高级编程语言,被广泛应用于人工智能、数据科学等领域"
print(count_words(text)) # 输出 13
```
这里使用`re.findall()`函数来匹配文本中所有的单词,并将它们转换为小写字母形式。然后使用Python内置函数`len()`来获取单词数量。