python统计英文句子的个数
时间: 2023-07-01 22:16:28 浏览: 95
可以使用Python中的正则表达式模块re来实现统计英文句子的个数。以下是一个示例代码:
```python
import re
text = "This is a sentence. This is another sentence. And this is a third sentence."
sentences = re.findall(r'\b[A-Z][^.!?]*[.!?]', text)
print("Number of sentences:", len(sentences))
```
输出结果为:
```
Number of sentences: 3
```
该代码首先定义了一个包含多个句子的文本字符串。然后,使用正则表达式模块re中的findall()函数来查找所有以大写字母开头、以句号、问号或感叹号结尾的句子。最后,使用len()函数计算找到的句子的数量并输出。
相关问题
python统计单词的个数
要在Python中统计单词的个数,你可以按照以下步骤操作:
1. 输入一个英文句子,并以回车符结束。
2. 将句子按空格分隔成单词。
3. 创建一个空的字典来存储每个单词及其出现的次数。
4. 遍历分隔后的单词列表,对于每个单词,如果它已经在字典中,将对应的值加1;否则,在字典中添加该单词并将值设置为1。
5. 统计结束后,输出字典中的键值对,即每个单词及其出现的次数。
6. 输出字典的长度,即单词的个数。
以下是一个示例代码:
```python
sentence = input("请输入一个英文句子:")
words = sentence.split()
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
for word, count in word_count.items():
print(word, ":", count)
print("单词的个数:", len(word_count))
```
统计英文句子单词的个数代码
以下是一个Python代码示例,用于统计英文句子中单词的个数:
```python
def count_words(sentence):
"""
统计英文句子中单词的个数
"""
words = sentence.split() # 根据空格分割单词
return len(words)
# 示例用法
s = "This is a sample sentence."
count = count_words(s)
print("单词个数:", count)
```
输出:
```
单词个数: 5
```
这个函数首先使用字符串的 `split()` 方法将句子分割成单词,然后返回单词列表的长度,即为单词的个数。