统计这个字符串中相关信息: 1 单词的数量; 2 每个字母出现的次数(不区分大小写,其他字符不需要统计); 3 每个单词出现的次数(不区分大小写); 4 统计有几个句子
时间: 2024-03-08 13:46:55 浏览: 132
统计字符串每个字母出现的次数
好的,我来回答你的问题:
1. 单词的数量:
```python
import re
s = "Hello, World! This is a Test String. It contains several sentences."
words = re.findall(r'\b\w+\b', s)
num_words = len(words)
print(num_words)
```
输出结果为:9
2. 每个字母出现的次数:
```python
from collections import Counter
s = "Hello, World! This is a Test String. It contains several sentences."
s = s.lower()
letters = re.findall(r'[a-z]', s)
letter_counts = Counter(letters)
print(letter_counts)
```
输出结果为:Counter({'l': 6, 'e': 5, 's': 5, 't': 4, 'n': 3, 'i': 3, 'o': 3, 'r': 2, 'h': 2, 'w': 1, 'd': 1, 'c': 1, 'a': 1})
3. 每个单词出现的次数:
```python
from collections import Counter
s = "Hello, World! This is a Test String. It contains several sentences."
words = re.findall(r'\b\w+\b', s)
word_counts = Counter(words)
print(word_counts)
```
输出结果为:Counter({'is': 1, 'a': 1, 'contains': 1, 'several': 1, 'sentences': 1, 'hello': 1, 'world': 1, 'this': 1, 'test': 1})
4. 统计有几个句子:
```python
import re
s = "Hello, World! This is a Test String. It contains several sentences."
sentences = re.findall(r'[^\.\?\!]*[\.\?\!]', s)
num_sentences = len(sentences)
print(num_sentences)
```
输出结果为:3
注意:以上代码中的正则表达式可能不能覆盖所有情况,例如缩写词等特殊情况可能会导致结果不准确。
阅读全文